依赖配置
<dependency>
<groupId>org.codelibs</groupId>
<artifactId>jcifs</artifactId>
<version>3.0.2</version>
</dependency>
Java类
java
package com.cim.ext.components;
import com.cim.ext.dto.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.codelibs.jcifs.smb.CIFSContext;
import org.codelibs.jcifs.smb.context.SingletonContext;
import org.codelibs.jcifs.smb.impl.NtlmPasswordAuthenticator;
import org.codelibs.jcifs.smb.impl.SmbFile;
import org.codelibs.jcifs.smb.impl.SmbFileInputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
/**
* 使用jcifs读取SMB共享文件的工具类
*/
@Component
@Slf4j
public class SmbFileReader {
@Value("${smb.user}")
private String smbUser;
@Value("${smb.password}")
private String smbPassword;
public SmbFile readSmbFile(String path) throws MalformedURLException{
// 创建认证器
NtlmPasswordAuthenticator auth = new NtlmPasswordAuthenticator(
null, // 域名,这里不需要填
smbUser,
smbPassword
);
// 创建CIFS上下文
CIFSContext context = SingletonContext.getInstance().withCredentials(auth);
// 初始化SMB文件对象
return new SmbFile(path, context);
}
public SmbFile[] list(String path) {
List<SmbFile> smbFiles = new ArrayList<>();
SmbFile dir = null;
try {
dir = readSmbFile(path);
if (!dir.exists()) {
log.warn("Directory not found: {}", path);
return null;
}
if (!dir.isDirectory()) {
log.warn("Path is not a directory: {}", path);
return null;
}
SmbFile[] files = dir.listFiles();
return files;
// smb://10.20.12.114/FreedoData/2023/
} catch (Exception ex) {
log.error("Failed to list files from path: {}", path, ex);
return null;
} finally {
if (dir != null) {
dir.close();
}
}
}
public SmbFile[] list2(String path) throws MalformedURLException {
SmbFile dir = new SmbFile(path);
try {
dir = readSmbFile(path);
if (!dir.exists()) {
log.warn("Directory not found: {}", path);
return null;
}
if (!dir.isDirectory()) {
log.warn("Path is not a directory: {}", path);
return null;
}
SmbFile[] files = dir.listFiles();
return files;
// smb://10.20.12.114/FreedoData/2023/
} catch (Exception ex) {
log.error("Failed to list files from path: {}", path, ex);
return null;
} finally {
if (dir != null) {
dir.close();
}
}
}
}
这个框架需要注意的是Smb的文件夹路径必须是/结尾,否则读取子文件夹会有 问题。