添加maven依赖
最早的 jcifs
库是 org.samba.jcifs
包,但是不支持 smb2协议
,因此需要替换成下面这个包:
<dependency>
<groupId>org.codelibs</groupId>
<artifactId>jcifs</artifactId>
<version>2.1.34</version>
</dependency>
使用方法
和之前的 jcifs
用法基本保持一致,唯一不同的是用户身份配置;
新库如何设置用户密码,网上找了一圈没有找到,github
上作者也没给使用说明,最后在源码中找到了方法:
public void test(){
Properties ps = new Properties();
ps.setProperty("jcifs.smb.client.domain", "域账户");
ps.setProperty("jcifs.smb.client.username", "用户名");
ps.setProperty("jcifs.smb.client.password", "密码");
// 这个 disable 属性默认为 false , 不设置为 true 的话读取共享文件会比较慢
ps.setProperty("jcifs.smb.client.dfs.disabled", "true");
CIFSContext cifs = new BaseContext(new PropertyConfiguration(ps));
// 文件夹
SmbFile dir = new SmbFile("smb://192.168.7.7/dir/", cifs );
// 读取文件
SmbFile file = new SmbFile("smb://192.168.7.7/file.zip", cifs );
// 判断是否为文件
file.isFile() // true | false
// 如果是目录的话可以读取目录下的文件
file.listFiles() // 返回 SmbFile[] 数组,可以自行递归
}
一下是可参考的源码:
// 在 PropertyConfiguration 中
....
this.logonShare = p.getProperty("jcifs.smb.client.logonShare", null);
this.defaultDomain = p.getProperty("jcifs.smb.client.domain", null);
this.defaultUserName = p.getProperty("jcifs.smb.client.username", null);
this.defaultPassword = p.getProperty("jcifs.smb.client.password", null);
this.netbiosHostname = p.getProperty("jcifs.netbios.hostname", null);
....