Java使用jcifs读取Windows的共享文件
作者:J2虾虾
这篇文章主要为大家详细介绍了Java如何使用jcifs实现读取Windows的共享文件,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
依赖配置
<dependency>
<groupId>org.codelibs</groupId>
<artifactId>jcifs</artifactId>
<version>3.0.2</version>
</dependency>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的文件夹路径必须是/结尾,否则读取子文件夹会有问题。
知识扩展
下面小编为大家整理了一些Java读取共享文件的方法,希望对大家有所帮助
1.java读取远程共享文件
例子一
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
public class ReadShareFile {
public static void main(String[] args) {
try {
SmbFile smbFile = new SmbFile(
"smb://test:test@192.168.1.1/out/test.txt");
int length = smbFile.getContentLength();// 得到文件的大小
byte buffer[] = new byte[length];
SmbFileInputStream in = new SmbFileInputStream(smbFile);
// 建立smb文件输入流
while ((in.read(buffer)) != -1) {
System.out.write(buffer);
System.out.println(buffer.length);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}例子二
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
public class TestReadSmb {
public static void main(String[] args){
String smbMachine="smb://test:test@10.108.23.200/temp/test.txt";
String localPath="D:\\temp";
File file=readFromSmb(smbMachine,localPath);
removeFile(file);
}
/** ***
* 从smbMachine读取文件并存储到localpath指定的路径
*
* @param smbMachine
* 共享机器的文件,如smb://xxx:xxx@10.108.23.112/myDocument/测试文本.txt,xxx:xxx是共享机器的用户名密码
* @param localpath
* 本地路径
* @return
*/
public static File readFromSmb(String smbMachine,String localpath){
File localfile=null;
InputStream bis=null;
OutputStream bos=null;
try{
SmbFile rmifile = new SmbFile(smbMachine);
String filename=rmifile.getName();
bis=new BufferedInputStream(new SmbFileInputStream(rmifile));
localfile=new File(localpath+File.separator+filename);
System.out.println("localfile=="+localfile);
bos=new BufferedOutputStream(new FileOutputStream(localfile));
int length=rmifile.getContentLength();
System.out.println("length=="+length);
byte[] buffer=new byte[length];
Date date=new Date();
bis.read(buffer);
bos.write(buffer);
Date end=new Date();
int time= (int) ((end.getTime()-date.getTime())/1000);
if(time>0)
System.out.println("用时:"+time+"秒 "+"速度:"+length/time/1024+"kb/秒");
} catch (Exception e){
System.out.println(e.getMessage());
}finally{
try {
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return localfile;
}
public static boolean removeFile(File file) {
return file.delete();
}
}2.Java读写Windows共享文件夹
InputStream in = null;
OutputStream out = null;
try {
//获取图片
File localFile = new File("C:/testjpg");
String remotePhotoUrl = "smb://share:admin@11/sharedFolder/"; //存放图片的共享目录
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS_");
SmbFile remoteFile = new SmbFile(remotePhotoUrl + "/" + fmtformat(new Date()) + localFilegetName());
remoteFileconnect(); //尝试连接
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[4096];
int len = 0; //读取长度
while ((len = inread(buffer, 0, bufferlength)) != -1) {
outwrite(buffer, 0, len);
}
outflush(); //刷新缓冲的输出流
}
catch (Exception e) {
String msg = "发生错误:" + egetLocalizedMessage();
Systemoutprintln(msg);
}
finally {
try {
if(out != null) {
outclose();
}
if(in != null) {
inclose();
}
}
catch (Exception e) {}
}
以上代码中,使用了JCIFS框架提供的SmbFile类,这个类和Java的File类比较相似,使用这个类的对象,可以处理远程文件的读写。使用File对象读取本地文件,然后使用SmbFile对象写入远程文件。SmbFile的connect()方法可以尝试连接远程文件夹,如果账号或密码错误,将抛出连接异常。
当下载远程文件时,使用SmbFile对象读取远程文件即可,代码如下:
InputStream in = null ;
ByteArrayOutputStream out = null ;
try {
//创建远程文件对象
String remotePhotoUrl = "smb://share:admin@11/sharedFolder/testjpg";
SmbFile remoteFile = new SmbFile(remotePhotoUrl);
remoteFileconnect(); //尝试连接
//创建文件流
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new ByteArrayOutputStream((int)remoteFilelength());
//读取文件内容
byte[] buffer = new byte[4096];
int len = 0; //读取长度
while ((len = inread(buffer, 0, bufferlength)) != - 1) {
outwrite(buffer, 0, len);
}
outflush(); //刷新缓冲的输出流
return outtoByteArray();
}
catch (Exception e) {
String msg = "下载远程文件出错:" + egetLocalizedMessage();
Systemoutprintln(msg);
}
finally {
try {
if(out != null) {
outclose();
}
if(in != null) {
inclose();
}
}
catch (Exception e) {}
}到此这篇关于Java使用jcifs读取Windows的共享文件的文章就介绍到这了,更多相关Java cifs读取Windows共享文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
