JAVA使用jcifs读取共享文件夹(SMB1,SMB2协议)

添加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);
....
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值