先科普一下,
SMB也就是CIFS,链接Smb操作如下:
//远程ip
String ip = "123.24.42";
String domain = "mydomain";
String username = "pascal";
String password = "123456";
String directory = "smb://123.24.42/test/a.txt";
System.setProperty("jcifs.smb.client.dfs.disabled", "true");
UniAddress dc = UniAddress.getByName(ip);
NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(domain, username, password);
SmbSession.logon(dc, authentication);
SmbFile file = new SmbFile(directory, authentication);
链接成功之后,可以进行和java.io.File中的很多操作,和File很类似,只不过换成了SmbFile取处理,比如
if (!file.exists()) {
log.info("not.exists.file.source.directory,directory.is:" + directory);
}
log.info("SmbFile.isDirectory:" + file.isDirectory());
if (file.isDirectory()) {
}
亲自链接并且进行操作之后,发现smb很慢,又看到了支持smb2协议和smb3协议的smbj,遂又研究了一下smbj的链接操作,如下:
//获取相关配置数据
String domain = fileConfig.getDomain();
String username = fileConfig.getUsername();
String password = fileConfig.getPassword();
String ip = fileConfig.getIp();
String source = fileConfig.getSource();
String folder = fileConfig.getFolder();
String directory = source + folder + "/";
String targetDir = fileConfig.getTarget();
log.info("file.source.directory.is:" + directory);
// 设置超时时间(可选)
SmbConfig config = SmbConfig.builder().withTimeout(120, TimeUnit.SECONDS)
.withTimeout(120, TimeUnit.SECONDS) // 超时设置读,写和Transact超时(默认为60秒)
.withSoTimeout(180, TimeUnit.SECONDS) // Socket超时(默认为0秒)
.build();
// 如果不设置超时时间 SMBClient client = new SMBClient();
SMBClient client = null;
Connection connection = null;
Session session = null;
DiskShare share = null;
client = new SMBClient(config);
connection = client.connect(ip);
AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
session = connection.authenticate(ac);
// 连接共享文件夹
share = (DiskShare) session.connectShare(source);
boolean folderExists = false;
log.info("share.list.size:" + share.list(directory).size());
long e = System.currentTimeMillis();
for (FileIdBothDirectoryInformation f : share.list(directory)) {
if (share.fileExists(filePath)) {
if (!folderExists) {
return ResultMessage.newInstance(2, "No file directory was found for the project code.", "");
}
log.info("SMB2Service.create.end");
return ResultMessage.newInstance(1, "", null);
}
}
相关参数配置如下:
com.smx.source=abc$
com.smx.ip=123.456.789
com.smx.domain=pascal
com.smx.username=pascal
com.smx.password=123456
com.smx.folder=my name/is pascal
这里要注意的是,list之后,下一步中的遍历的路径就是已经在share的文件夹下的,别写多了,不然找不到文件所在位置 ,还有链接share的时候,只到$之前就好了,后面的具体路径不要,这是一个shareName,然后等链接了之后,再具体加下级路径,还有最后要注意share,session,clientd的流的关闭.