首先开启服务,打开控制面板点击程序
maven版本存在于SMB协议的兼容问题
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.3</version>
</dependency>
public static void getRemoteFile() {
// 创建远程文件对象
// smb://ip地址/共享的路径/...
// smb://用户名:密码@ip地址/共享的路径/...
String remoteUrl = "smb://Administrator:password@ip/Test/";
smbTransferFile(remoteUrl, "E:\\nacos-server-2.2.1.zip");
SmbFile[] smbFiles = smbGetFiles(remoteUrl);
if (Objects.nonNull(smbFiles)) {
for (SmbFile smbFile : smbFiles) {
System.out.println("smbFile路径:" + smbFile.getUncPath());
}
}
}
/**
* @return
* @Description 从共享目录读取文件
* @Param shareDirectory 共享目录
*/
private static SmbFile[] smbGetFiles(String remoteUrl) {
try {
SmbFile remoteFile = new SmbFile(remoteUrl);
remoteFile.connect();//尝试连接
if (remoteFile.exists()) {
// 获取共享文件夹中文件列表
return remoteFile.listFiles();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
/**
* @Description 向共享目录上传文件
* @Param shareDirectory 共享目录
* @Param localFilePath 本地目录中的文件路径
*/
public static void smbTransferFile(String shareDirectory, String fileName, byte[] localFile) {
InputStream in = null;
OutputStream out = null;
try {
SmbFile remoteFile= new SmbFile(shareDirectory +fileName);
SmbFile mkFlag = new SmbFile(shareDirectory);
if(!mkFlag.exists()){
mkFlag.mkdirs();
}
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
out.write(localFile);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (Objects.nonNull(out)) {
out.close();
}
if (Objects.nonNull(in)) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @Description 向共享目录上传文件
* @Param shareDirectory 共享目录
* @Param localFilePath 本地目录中的文件路径
*/
public static void smbTransferFile(String shareDirectory, String localFilePath) {
InputStream in = null;
OutputStream out = null;
try {
File localFile = new File(localFilePath);
String fileName = localFile.getName();
SmbFile remoteFile = new SmbFile(shareDirectory + fileName);
in = new BufferedInputStream(Files.newInputStream(localFile.toPath()));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (Objects.nonNull(out)) {
out.close();
}
if (Objects.nonNull(in)) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~~
因篇幅问题不能全部显示,请点此查看更多更全内容