apache commons-vfs访问认证

Apache Commons-VFS 为我们提供了对各种文件系统的标准访问接口,除了常用的文件类型( zip gzip jar ,本地文件系统)之外还可以直接操作多种服务器文件,如 ftp sftp 等。在进行服务器文件操作时通常要指定访问的用户名和密码。接下来就以 ftp 服务器的文件系统的连接为例进行介绍。

注:涉及到的 Apache Commons-VFS 版本为 3.1

1.       文件访问 uri 中指定认证信息

这也是最简单直接的一种访问,文件的 uri 格式为:

schema://[ 用户名 ]:[ 密码 ]@[host]:[port][ 文件 path]

ftp 为例就是: ftp://admin:[email protected]:21/data

获得 FileObject 的关键语句如下:

FileObject fileObj = fsManager.resolveFile(vfsPath);
String vfsPath = "ftp://admin:[email protected]:21/data";
FileObject fileObj = fsManager.resolveFile(vfsPath);

2.       密码加密

上例的连接方式可以简单直接的完成远程 ftp 的连接,但是缺点也是比较明显的,那就是密码已明文形式存在的。出于安全的考虑,接下来对密码进行加密处理。

密码密文的生成的方式可以通过 commons-vfs 提供的工具类:

java -cp commons-vfs-2.0.jar org.apache.commons.vfs2.util.EncryptUtil encrypt 123456 

输入的密码 123456 加密后的结果为 0471BC0FDAC99FF9EA9E1CDD3F350026

现在我们的连接方式也变成了:

String vfsPath = "ftp://admin:{0471BC0FDAC99FF9EA9E1CDD3F350026}@192.168.1.1:21/data";

其实 vfs 中执行这个加密的操作也很简单,只有下面两句代码:

Cryptor cryptor = CryptorFactory.getCryptor();
String pwdEncrypt = cryptor.encrypt(yourpassword);

3.  通过 FileSystemOptions 方式

除了在 uri 中显示指定认证信息之外还可以通过 FileSystemOptions 来完成。

StaticUserAuthenticator auth = new StaticUserAuthenticator("username", "password", null);
FileSystemOptions opts = new FileSystemOptions(); DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile("ftp://192.168.1.1:21/data", opts);

但是这种方式指定密码时就不能支持密文的方式了。

4.       一点小技巧

通过 VFS.getManager() 方式获得的 FileSystemManager 对应的实现类为 StandardFileSystemManager ,在其抽象基类中有一个 setBaseFile () 方法可以设置本次会话的根目录,这样在文件操作的 uri 中就可以只设定相对于该 basefile 的相对路径了。

Set the base file using setBaseFile() . The base file is used to resolve relative URI passed to resolveFile() . This step is optional.

猜你喜欢

转载自han-zw.iteye.com/blog/1745466