`
sisi1984117
  • 浏览: 151626 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

【转】VFS&&SFTP相关

阅读更多

第一部分

Commons Virtual File System

文章分类:Java编程

VFS

Commons Virtual File System (VFS)提供了一种能够统一访问不同文件系统的抽象层。这个组件能够配置为同时连接一个或多个的文件系统。在Linux操作系统下也是比较容易的。

VFS支持下列文件系统:

  • Local files – 本地文件和文件夹(file://)
  • Zip, jar, tar, tgz, tbz2, gzip, bzip2 – 不同的压缩格式(zip://, jar://, etc.)
  • CIFS – Samba服务或Windows共享(smb://)
  • FTP – FTP服务器(ftp://)
  • HTTP和HTTPS (http://)
  • SFTP – SSH或SCP服务器(sftp://)
  • Temporary files (tmp://)
  • WebDAV – Web-based Distributed Authoring and Versioning (webdav://)
  • Resource from class loader – 使用ClassLoader获取类或其他资源(res://)

        这个组件对那些需要访问不同类型的文件系统的应用程序来说十分有用。举例来说:一个桌面搜索工具同这个框架非常类似。它提供用户搜索文件或文件的内容。另外一个例子就是集成Windows IE浏览器类似的功能到Java应用程序。

        范例应用程序是一个工具,它使用Commons VFS来在文件夹中查询Zip和Jar文件。应用程序没有提供用户界面,但是提供了一个测试用例来证明它能良好的工作。可以在in.co.narayanan.commons.vfs 找到范例和测试代码。按顺序运行范例应用程序,下载源码压缩包,运行Ant构建脚本来创建Commons VFS库。Ant脚本会自动下载其他依赖的库文件。最后通过JUnit测试来启动范例应用程序。[in.co.narayanan.commons.vfs.TestSearchBuddy ]

        最初的使用Commons VFS的想法是创建一个提供支持每种文件类型并能够由DefautFileSystemManager引用的Manager实例。为深层次的操作,需要通过manager的resolveFile方法获取FileObject实例。Manager和FileObject提供了不同的方法,可以在 JavaDoc中找到他们的详细说明。下一段文字描述在搜索工具中如何使用Commons VFS API。

        清单6通过in.co.narayanan.commons.vfs.SearchBuddy类中初始化DefaultFileSystemManager类的代码片断。
 
清单6.初始化文件系统管理器
/**
 * Initialize the DefaultFileSystemManager to support
 * file, zip and jar providers. A virtual file system
 * is created and passed to the SearchableVirtualFileSystem
 * decorator class.
 *
 * @throws SearchException Error in initializing the file
 *       FileSystemManager
 */
private void init() throws SearchException {
 defFileSysMgr = new DefaultFileSystemManager();
 
 try {
 
  defFileSysMgr.addProvider("file", new DefaultLocalFileProvider());
  defFileSysMgr.addProvider("zip", new ZipFileProvider());
  defFileSysMgr.addProvider("jar", new JarFileProvider());
  defFileSysMgr.init();
 
  // 创建虚拟文件系统
  VirtualFileSystem vfs =
  (VirtualFileSystem)defFileSysMgr.createVirtualFileSystem("vfs://").getFileSystem();
 
  searchableVfs = new SearchableVirtualFileSystem(vfs);
   
 } catch (FileSystemException e) {
  throw new SearchException("Unable to initialize the FileSystemManager.", e);
 }
}
        高亮代码行为在文件系统中查询本地普通文件、zip文件、jar文件增加providers。这段代码创建一个VirtualFileSystem类的实例,这个类可以用来装备其它的文件系统。

        清单7时测试用例类TestSearchBuddy的代码片断,它说明范例应用程序如合查找文件。


 
清单7. 使用查询工具
/**
 * Adds the folder, zip, and a jar file to search
 *
 * @throws Exception Error in the test.
 */
public void testSearchInZips() throws Exception {
 SearchBuddy searchTool = new SearchBuddy();
 searchTool.addSearchableZip("testroot.zip");
 searchTool.addSearchableJar("testjar.jar");
 searchTool.addSearchableFolder(".");
  
 System.out.println("Searching for news.txt");
 searchTool.search("news", "txt");
  
 System.out.println("Searching for Range.class");
 searchTool.search("range", "class");
  
 System.out.println("Searching for test.xml");
 searchTool.search("test", "xml");
 
 System.out.println("Searching for *.properties");
 searchTool.search(null, "properties");
 searchTool.close();

}
转自:http://yangzb.iteye.com/blog/600636

 

第二部分Java sftp 实现例子

package net.xwolf.ultility;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class FtpImpl{
    
    private String host = "127.0.0.1";
    private String username="MingMac";
    private String password="×××";
    private int port = 22;
    private ChannelSftp sftp = null;
    private String localPath = "/Users/MingMac/Documents";
    private String remotePath = "/Users/MingMac/MyDocuments";
    private String fileListPath = "/Users/MingMac/Documents/Java/workspace/MyTools/conf/file.txt";
    private final String seperator = "/";
    
    /**
     * connect server via sftp
     */
    public void connect() {
        try {
            if(sftp != null){
                System.out.println("sftp is not null");
            }
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            System.out.println("Session created.");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            System.out.println("Session connected.");
            System.out.println("Opening Channel.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            System.out.println("Connected to " + host + ".");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * Disconnect with server
     */
    public void disconnect() {
        if(this.sftp != null){
            if(this.sftp.isConnected()){
                this.sftp.disconnect();
            }else if(this.sftp.isClosed()){
                System.out.println("sftp is closed already");
            }
        }

    }

    public void download() {
        // TODO Auto-generated method stub
        

    }
    
    
    private void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * upload all the files to the server
     */
    public void upload() {
        List<String> fileList = this.getFileEntryList(fileListPath);
        try {
            if(fileList != null){
                for (String filepath : fileList) {
                    String localFile = this.localPath + this.seperator+ filepath;
                    File file = new File(localFile);
                    
                    if(file.isFile()){
                        System.out.println("localFile : " + file.getAbsolutePath());
                        String remoteFile = this.remotePath + this.seperator + filepath;
                        System.out.println("remotePath:" + remoteFile);
                        File rfile = new File(remoteFile);
                        String rpath = rfile.getParent();
                        try {
                            createDir(rpath, sftp);
                        } catch (Exception e) {
                            System.out.println("*******create path failed" + rpath);
                        }

                        this.sftp.put(new FileInputStream(file), file.getName());
                        System.out.println("=========upload down for " + localFile);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SftpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    /**
     * create Directory
     * @param filepath
     * @param sftp
     */
    private void createDir(String filepath, ChannelSftp sftp){
        boolean bcreated = false;
        boolean bparent = false;
        File file = new File(filepath);
        String ppath = file.getParent();
        try {
            this.sftp.cd(ppath);
            bparent = true;
        } catch (SftpException e1) {
            bparent = false;
        }
        try {
            if(bparent){
                try {
                    this.sftp.cd(filepath);
                    bcreated = true;
                } catch (Exception e) {
                    bcreated = false;
                }
                if(!bcreated){
                    this.sftp.mkdir(filepath);
                    bcreated = true;
                }
                return;
            }else{
                createDir(ppath,sftp);
                this.sftp.cd(ppath);
                this.sftp.mkdir(filepath);
            }
        } catch (SftpException e) {
            System.out.println("mkdir failed :" + filepath);
            e.printStackTrace();
        }
        
        try {
            this.sftp.cd(filepath);
        } catch (SftpException e) {
            e.printStackTrace();
            System.out.println("can not cd into :" + filepath);
        }
        
    }
    /**
     * get all the files need to be upload or download
     * @param file
     * @return
     */
    private List<String> getFileEntryList(String file){
        ArrayList<String> fileList = new ArrayList<String>();
        InputStream in = null;
        try {
            
            in = new FileInputStream(file);
            InputStreamReader inreader = new InputStreamReader(in);
            
            LineNumberReader linreader = new LineNumberReader(inreader);
            String filepath = linreader.readLine();
            while(filepath != null){
                fileList.add(filepath);
                filepath = linreader.readLine();
            }
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(in != null){
                in = null;
            }
        }

        return fileList;
    }

    /**
     * @return the host
     */
    public String getHost() {
        return host;
    }

    /**
     * @param host the host to set
     */
    public void setHost(String host) {
        this.host = host;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the port
     */
    public int getPort() {
        return port;
    }

    /**
     * @param port the port to set
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * @return the sftp
     */
    public ChannelSftp getSftp() {
        return sftp;
    }

    /**
     * @param sftp the sftp to set
     */
    public void setSftp(ChannelSftp sftp) {
        this.sftp = sftp;
    }

    /**
     * @return the localPath
     */
    public String getLocalPath() {
        return localPath;
    }

    /**
     * @param localPath the localPath to set
     */
    public void setLocalPath(String localPath) {
        this.localPath = localPath;
    }

    /**
     * @return the remotePath
     */
    public String getRemotePath() {
        return remotePath;
    }

    /**
     * @param remotePath the remotePath to set
     */
    public void setRemotePath(String remotePath) {
        this.remotePath = remotePath;
    }

    /**
     * @return the fileListPath
     */
    public String getFileListPath() {
        return fileListPath;
    }

    /**
     * @param fileListPath the fileListPath to set
     */
    public void setFileListPath(String fileListPath) {
        this.fileListPath = fileListPath;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FtpImpl ftp= new FtpImpl();
        ftp.connect();
        ftp.upload();
        ftp.disconnect();
        System.exit(0);
    }


}

 

转自:http://topic.csdn.net/u/20091115/21/09c41943-fb8b-4189-af52-0e7a47152afd.html

最近写的一个JAVA实现SFTP的实例:

/*
* Created on 2009-9-14
* Copyright 2009 by www.xfok.net. All Rights Reserved
*
*/

package net.xfok.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
* @author YangHua
* 转载请注明出处:http://www.xfok.net/2009/10/124485.html
*/
public class MySFTP {

/**
* 连接sftp服务器
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
} catch (Exception e) {

}
return sftp;
}

/**
* 上传文件
* @param directory 上传的目录
* @param uploadFile 要上传的文件
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file=new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @param sftp
*/
public void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file=new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 删除文件
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 列出目录下的文件
* @param directory 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException{
return sftp.ls(directory);
}

public static void main(String[] args) {
MySFTP sf = new MySFTP();
String host = "192.168.0.1";
int port = 22;
String username = "root";
String password = "root";
String directory = "/home/httpd/test/";
String uploadFile = "D:\\tmp\\upload.txt";
String downloadFile = "upload.txt";
String saveFile = "D:\\tmp\\download.txt";
String deleteFile = "delete.txt";
ChannelSftp sftp=sf.connect(host, port, username, password);
sf.upload(directory, uploadFile, sftp);
sf.download(directory, downloadFile, saveFile, sftp);
sf.delete(directory, deleteFile, sftp);
try{
sftp.cd(directory);
sftp.mkdir("ss");
System.out.println("finished");
}catch(Exception e){
e.printStackTrace();
}
}
}

<script type="text/javascript"></script>

第五部分使用VFS进行SFTP网络传输
分享到:
评论

相关推荐

    commons-vfs-2.1源码

    commons-vfs-2.1源码

    kettle必须的包

    Unable to get VFS File object for filename '' : Unknown scheme "sftp" in URI "{1}". 缺少jar包

    commons-logging-1.2.jar commons-vfs-2.2.jar

    commons-logging-1.2.jar commons-vfs-2.2.jar,用以sftp上传现在

    vfs-utils:VFS实用程序-开源

    Apache Commons VFS实用程序,例如到Apache Mina FTP服务器的桥接器,到Apache Mina SSHD / SCP / SFTP服务器的桥接器以及可脚本化的Java Shell /控制台,可提供带有VFS文件系统命令和操作的命令行界面。

    sftpLoad:使用 sftp 上传文件到远程服务器

    sftp加载 使用 sftp 上传文件到远程服务器 ... stpTransfer.java:在本地计算机和远程服务器之间传输文件:1) 使用 sftp 进行安全文件传输 2) 使用 Apache Commons VFS 提供单个 API 来访问文件系统(例如 SFTP)

    VFSManager - A Commons VFS GUI-开源

    使用Java / SWT编写的Apache Commons VFS API的图形用户界面:多平台,能够在多个文件系统(例如ftp,sftp,smb,webdav等)中管理文件。

    VFS-Resource-Adapter:VFS 入站资源适配器

    VFS-资源-适配器 VFS 入站资源适配器 该项目是在入站资源适配器中使用 commons vfs2 文件监视器的示例。 所有这些都在 TomEE web 项目中可用 信息 在 Web 模块中的 MDB 中配置 sftp 详细信息 构建父 pom mvn tomee...

    破解版mdbdriver.jar

    SFTP URL to the SFTP-server directory (syntax: sftp://user:password@hostname[:port]/[dirpath/]mdbfile, also required third-party libraries Commons VFS and JSch for this protocol), e.g.: jdbc:jstels:...

    gvfs:https的只读镜像

    GVFS ... 对于与安全相关的问题,请使用 。 有关获取调试日志的信息,请参见 。 问问题 如有疑问,请使用gvfs邮件列表 。 有关订阅信息,请参见 。 或者,可以使用irc://irc.gnome.org/nautilus。

    esup-filemanager:ESUP 文件管理器是一个 JSR286 Portlet。 Esup 文件管理器允许用户对其 HomeDirs 执行文件管理

    使用 apache commons vfs -&gt; 支持的文件系统在这里: : - uri like file:///home/bob 工作例如 - ftp 和 sftp ok ... CIFS 支持(使用 JCIFS) Webdav 支持(使用 Sardine) CMIS 支持(Apache 化学)。 使用 ...

    ETL工具Kettle用户手册

    目录 Kettle 3.0 用户手册 ...................................................................................................................... 1 Kettle 3.0 用户手册 .....................................

Global site tag (gtag.js) - Google Analytics