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{
// 創(chuàng)建認(rèn)證器
NtlmPasswordAuthenticator auth = new NtlmPasswordAuthenticator(
null, // 域名,這里不需要填
smbUser,
smbPassword
);
// 創(chuàng)建CIFS上下文
CIFSContext context = SingletonContext.getInstance().withCredentials(auth);
// 初始化SMB文件對(duì)象
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();
}
}
}
}這個(gè)框架需要注意的是Smb的文件夾路徑必須是/結(jié)尾,否則讀取子文件夾會(huì)有問(wèn)題。
知識(shí)擴(kuò)展
下面小編為大家整理了一些Java讀取共享文件的方法,希望對(duì)大家有所幫助
1.java讀取遠(yuǎn)程共享文件
例子一
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讀取文件并存儲(chǔ)到localpath指定的路徑
*
* @param smbMachine
* 共享機(jī)器的文件,如smb://xxx:xxx@10.108.23.112/myDocument/測(cè)試文本.txt,xxx:xxx是共享機(jī)器的用戶名密碼
* @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("用時(shí):"+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讀寫(xiě)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; //讀取長(zhǎng)度
while ((len = inread(buffer, 0, bufferlength)) != -1) {
outwrite(buffer, 0, len);
}
outflush(); //刷新緩沖的輸出流
}
catch (Exception e) {
String msg = "發(fā)生錯(cuò)誤:" + egetLocalizedMessage();
Systemoutprintln(msg);
}
finally {
try {
if(out != null) {
outclose();
}
if(in != null) {
inclose();
}
}
catch (Exception e) {}
}
以上代碼中,使用了JCIFS框架提供的SmbFile類,這個(gè)類和Java的File類比較相似,使用這個(gè)類的對(duì)象,可以處理遠(yuǎn)程文件的讀寫(xiě)。使用File對(duì)象讀取本地文件,然后使用SmbFile對(duì)象寫(xiě)入遠(yuǎn)程文件。SmbFile的connect()方法可以嘗試連接遠(yuǎn)程文件夾,如果賬號(hào)或密碼錯(cuò)誤,將拋出連接異常。
當(dāng)下載遠(yuǎn)程文件時(shí),使用SmbFile對(duì)象讀取遠(yuǎn)程文件即可,代碼如下:
InputStream in = null ;
ByteArrayOutputStream out = null ;
try {
//創(chuàng)建遠(yuǎn)程文件對(duì)象
String remotePhotoUrl = "smb://share:admin@11/sharedFolder/testjpg";
SmbFile remoteFile = new SmbFile(remotePhotoUrl);
remoteFileconnect(); //嘗試連接
//創(chuàng)建文件流
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new ByteArrayOutputStream((int)remoteFilelength());
//讀取文件內(nèi)容
byte[] buffer = new byte[4096];
int len = 0; //讀取長(zhǎng)度
while ((len = inread(buffer, 0, bufferlength)) != - 1) {
outwrite(buffer, 0, len);
}
outflush(); //刷新緩沖的輸出流
return outtoByteArray();
}
catch (Exception e) {
String msg = "下載遠(yuǎn)程文件出錯(cuò):" + egetLocalizedMessage();
Systemoutprintln(msg);
}
finally {
try {
if(out != null) {
outclose();
}
if(in != null) {
inclose();
}
}
catch (Exception e) {}
}到此這篇關(guān)于Java使用jcifs讀取Windows的共享文件的文章就介紹到這了,更多相關(guān)Java cifs讀取Windows共享文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)Flappy Bird游戲源代碼
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)Flappy Bird游戲源代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
基于Java實(shí)現(xiàn)動(dòng)態(tài)切換ubuntu壁紙功能
這篇文章主要為大家詳細(xì)介紹了如何使用 Java 在 Ubuntu Linux 系統(tǒng)中實(shí)現(xiàn)自動(dòng)切換壁紙的示例程序,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
java List循環(huán)與Map循環(huán)的總結(jié)
這篇文章主要介紹了java List循環(huán)與Map循環(huán)的總結(jié)的相關(guān)資料,并附代碼實(shí)例,幫助大家學(xué)習(xí)理解,需要的朋友可以參考下2016-11-11
在idea2023中使用SpringBoot整合Lombok全過(guò)程及詳細(xì)用法
Lombok項(xiàng)目是一個(gè)java庫(kù),它可以自動(dòng)插入到編輯器和構(gòu)建工具中,增強(qiáng)java的性能,本文詳細(xì)給大家介紹了在idea2023中使用SpringBoot整合Lombok全過(guò)程及詳細(xì)用法,需要的朋友可以參考下2023-09-09
Spring 與 JDK 線程池的簡(jiǎn)單使用示例詳解
這篇文章主要介紹了Spring 與 JDK 線程池的簡(jiǎn)單使用,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09
解析Java和Eclipse中加載本地庫(kù)(.dll文件)的詳細(xì)說(shuō)明
本篇文章是對(duì)Java和Eclipse中加載本地庫(kù)(.dll文件)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Aop動(dòng)態(tài)代理和cglib實(shí)現(xiàn)代碼詳解
這篇文章主要介紹了Aop動(dòng)態(tài)代理和cglib實(shí)現(xiàn)代碼詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12
springboot項(xiàng)目mysql-connector-java默認(rèn)版本如何查看
這篇文章主要介紹了springboot項(xiàng)目mysql-connector-java默認(rèn)版本如何查看問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
maven中的maven-antrun-plugin插件示例詳解
maven-antrun-plugin?是?Maven?生態(tài)中一個(gè)強(qiáng)大的工具,尤其適合需要復(fù)用?Ant?腳本或?qū)崿F(xiàn)復(fù)雜構(gòu)建邏輯的場(chǎng)景,然而,過(guò)度使用可能導(dǎo)致構(gòu)建腳本復(fù)雜化,建議權(quán)衡利弊后合理使用,這篇文章主要介紹了maven中的maven-antrun-plugin插件詳解,需要的朋友可以參考下2025-06-06
Spring Boot Actuator應(yīng)用監(jiān)控與管理的詳細(xì)步驟
SpringBootActuator是SpringBoot的監(jiān)控工具,提供健康檢查、性能指標(biāo)、日志管理等核心功能,支持自定義和擴(kuò)展端點(diǎn),并通過(guò)SpringSecurity配置安全權(quán)限,便于生產(chǎn)環(huán)境應(yīng)用監(jiān)控與管理,本文給大家介紹Spring Boot Actuator應(yīng)用監(jiān)控與管理的相關(guān)知識(shí),感興趣的朋友一起看看吧2025-07-07

