为了项目要求SFTP很无奈地上了阿帕奇的VFS。
网上对VFS的介绍很少,官方的DOC基本可以忽略。
在发现没有SFTP根目录访问权限的情况下,开始对VFS调试。
终于解决了根目录的重定向问题。
与大家分享一下:
/**
*
* @DESCRIPION :init environment
* @Create on: 2010-5-24 下午04:01:52
* @Author : jack
* @return void
* @throws Exception
* @throws AccessException
*/
public void init() throws Exception {
// SFTP 供应者
SftpFileProvider fp = new SftpFileProvider();
// ZIP 供应者
// ZipFileProvider zp = new ZipFileProvider();
ZipFileProvider zp = new ZipFileProvider();
// 缺省本地文件供应者
DefaultLocalFileProvider lf = new DefaultLocalFileProvider();
try {
// common-vfs 文件管理器的使用范例
mgr.addProvider("sftp", fp);
// Zip, jar, tar, tgz, tbz2, gzip, bzip2 – 不同的压缩格式(zip://, jar://,
// etc.)
mgr.addProvider("zip", zp);
mgr.addProvider("file", lf);
mgr.addExtensionMap("zip", "zip");
mgr.addMimeTypeMap("application/zip", "zip");
mgr.setFilesCache(new DefaultFilesCache());
mgr.init();
is_inited = true;
} catch (FileSystemException e) {
// 此处应该改为log
e.printStackTrace();
}
}
首先是初始化环境,不多罗嗦,网上多的是。
/**
*
* @DESCRIPION :用相对路径访问FTP
* @Create on: 2010-5-25 上午10:05:12
* @Author : jack
* @param url
* @return
* @throws FileSystemException
* @return FileObject
*/
public FileObject SearchFtpFile(String url) throws FileSystemException {
FileObject ftpFile = mgr.resolveFile(getBase(), url);
return ftpFile;
}
很简单的访问方法,例如根目录为sftp://username:password@ip:port/
而登录FTP时没有根目录的权限,只能访问sftp://username:password@ip:port/USERDIR
那么你现在的根目录就要改为/USERDIR了。
/**
*
* @DESCRIPION :get the base root
* @Create on: 2010-6-7 下午02:23:02
* @Author : jack
* @return
* @throws FileSystemException
* @return FileObject
*/
protected FileObject getBase() throws FileSystemException {
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
FileObject root = mgr.resolveFile(getSftpBaseURL(), opts);
return root;
}
public static String getSftpBaseURL() {
return System.getProperty("b2channel.url.sftp.base.root",
"sftp://XXX:XXX@10.203.27.11:22/");
}
获取根路径的方法,将他作为参数,之后的方法都用它来相对访问。
/**
*
* @DESCRIPION :main test method
* @Create on: 2010-5-24 下午04:01:06
* @Author : jack
* @param args
* @return void
*/
public static void main(String[] args) {
VFSLifeCycleHandeler instance = new VFSLifeCycleHandeler();
try {
instance.init();
FileObject ftpFile = instance.SearchFtpFile("Message");
Dir(ftpFile);
} catch (FileSystemException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
instance.destory();
}
}
测试可以通过
希望对大家有所帮助,无私奉献了!