Java使用jcifs读取Windows的共享文件

 更新时间:2026年04月03日 09:14:48   作者: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共享文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java多主机通信性能优化的方法

    Java多主机通信性能优化的方法

    本文给大家介绍了Java多主机通信性能优化的核心策略,包括线程池精细化配置、连接复用、异步非阻塞IO、数据传输优化、超时与重试策略等,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2026-01-01
  • Java实现鼠标随机移动效果的示例代码

    Java实现鼠标随机移动效果的示例代码

    有的时候我们需要鼠标一直滑动的情况,为了节省时间,本文用Java语言写了一个脚本,可以实现鼠标随机移动,感兴趣的小伙伴可以了解一下
    2022-05-05
  • Java中的JVM内存分析与故障排查指南

    Java中的JVM内存分析与故障排查指南

    Java虚拟机(JVM)是Java应用的运行时环境,其内存管理机制直接影响着应用的性能和稳定性,本文将介绍JVM内存分析的基本方法,重点介绍如何使用jmap、jhat和VisualVM等工具进行内存分析,并探讨常见的内存泄漏排查方法,需要的朋友可以参考下
    2025-11-11
  • java poi读取excel操作示例(2个代码)

    java poi读取excel操作示例(2个代码)

    这篇文章主要介绍了使用POI读取EXCEL文件的方法,代码大家可以参考使用
    2013-12-12
  • Java之操作Redis案例讲解

    Java之操作Redis案例讲解

    这篇文章主要介绍了Java之操作Redis案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • 详解eclipse将项目打包成jar文件的两种方法及问题解决方法

    详解eclipse将项目打包成jar文件的两种方法及问题解决方法

    本文给大家介绍了eclipse中将项目打包成jar文件的两种方法及其遇到问题解决方法,本文图文并茂给大家介绍的非常详细,需要的朋友可以参考下
    2017-12-12
  • ReentrantLock源码详解--条件锁

    ReentrantLock源码详解--条件锁

    这篇文章主要介绍了ReentrantLock源码之条件锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面我们来一起学习一下吧
    2019-06-06
  • IDEA配置Tomcat本地路径实现过程

    IDEA配置Tomcat本地路径实现过程

    文章介绍了在将项目从Eclipse迁移到IntelliJ IDEA时,配置Tomcat虚拟路径与本地路径的过程,通过修改Tomcat的server.xml文件和IDEA的运行配置,实现了成功部署和运行
    2026-02-02
  • IDEA生成javadoc的实现步骤

    IDEA生成javadoc的实现步骤

    Javadoc是一种用于生成API文档的工具,它可以根据代码中特定格式的注释自动生成文档,本文主要介绍了IDEA生成javadoc的实现步骤,感兴趣的可以了解一下
    2023-10-10
  • OpenFeign无法远程调用问题及解决

    OpenFeign无法远程调用问题及解决

    文章介绍了在使用Feign客户端时遇到的读超时问题,并分析了原因是系统启动时未先加载Nacos配置,为了解决这个问题,建议将Nacos配置放在`bootstrap.yml`文件中,以便项目启动时优先加载Nacos配置
    2024-11-11

最新评论