使用Java局域网读取windows共享文件夹(smb协议)


前言

使用Java局域网读取windows共享文件夹(smb协议)


一、smb协议简单了解

SMB(全称是Server Message Block)是一个网络协议名,它能被用于Web连接和客户端与服务器之间的信息沟通。SMB最初是IBM的贝瑞·费根鲍姆(Barry Feigenbaum)研制的,其目的是将DOS操作系统中的本地文件接口“中断13”改造为网络文件系统。

二、demo

1.设置文件夹为共享文件夹

(1)右键文件夹点击属性
右键点击属性

(2)点击共享
在这里插入图片描述
(3)添加everyone 点击共享
在这里插入图片描述
(4)点击网络共享中心配置
在这里插入图片描述
在这里插入图片描述
(4)另一台局域网电脑怎么访问共享的文件夹。
在这里插入图片描述

2.Java代码

(1)用到的Maven依赖

<!--smb协议获取共享文件夹内容-->
        <dependency>
            <groupId>jcifs</groupId>
            <artifactId>jcifs</artifactId>
            <version>1.3.17</version>
        </dependency>

(2)获取共享文件夹下所有的文件

/**
     * 读取共享文件夹下的所有文件(文件夹)的名称
     *
     * @param "smb://192.168.1.215/ecg/2022-09-29/ 
     */
    public static SmbFile[] getSharedFileList(String smbFileUrl) {
        SmbFile smbFile;
        try {
            smbFile = new SmbFile(smbFileUrl);
            if (!smbFile.exists()) {
                log.error("文件夹不存在");
            } else {
                SmbFile[] files = smbFile.listFiles();
                return files;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
        return null;
    }

(2)下载文件到指定文件夹

/**
     * 下载文件到指定文件夹
     * @param remoteUrl 远程文件夹路径
     * @param fileName 文件名称
     * @param localDir 要下载到本地的路径
     * @param localFileName 下载到本地的文件重命名名称
     */
    public static void downloadFileToFolder(String remoteUrl, String fileName, String localDir, String localFileName) {
        InputStream in = null;
        OutputStream out = null;
        try {
            File dir = new File(localDir);
            if(!dir.exists()){
                dir.mkdir();
            }
            SmbFile remoteFile = new SmbFile(remoteUrl  + "/" + fileName);
            File localFile = new File(localDir + "/" + localFileName);
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

总结

注意要处与同一局域网内

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值