JAVA 访问windows共享文件夹

一、使用技术

JCIFS框架对Windows共享文件夹进行读写,使用了SMB通信协议,它为局域网内不同的计算机之间提供文件和打印机等资源共享服务 。

二、共享文件夹设置

  1. 测试共享文件夹机器windows版本为win10家庭版.首先在应用和功能列表里找到在这里插入图片描述

    2.然后在windows功能中打开SMB功能
    在这里插入图片描述
    在这里插入图片描述
    最后把一个把电脑上任意一个文件夹设置成共享.设置到这里就完成了!

三、版本选择

最开始我是使用的最新版本的

<dependency>
            <groupId>org.samba.jcifs</groupId>
            <artifactId>jcifs</artifactId>
            <version>1.3.3</version>
 </dependency>

先贴上我的测试代码

package com.plover.system.util;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

/**
 * @author : AllenJ
 * @since : 2021/5/31
 */
public class SmbUtil {

    private static final String USER_DOMAIN = "";  //域账号,没有可以不填
    private static final String USER_NAME = "test";  //账号
    private static final String USER_PWS = "123456";  //密码

    public static void main(String[] args) {
        String shareDir = "smb://192.168.4.19/x04shareTest/";
        getFileList(shareDir);
//        smdDownload(shareDir, "d://home/smb");
    }

    /**
     * @date 2020-03-19
     * 遍历指定目录下的文件
     * shareDirectory: smb://192.168.4.19/x804shareTest/
     */
    private static void getFileList(String shareDirectory) {
        // 域服务器验证
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, USER_NAME, USER_PWS);
        SmbFile remoteFile = null;
        try {
            remoteFile = new SmbFile(shareDirectory, auth);
           
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            if (remoteFile.exists()) {
                SmbFile[] files = remoteFile.listFiles();
                for (SmbFile f : files) {
                    System.out.println(f.getName());
                }
            }
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Param shareUrl:smb://192.168.4.19/x804shareTest/abc.jpg
     * @Param localDirectory 本地目录,如d://home/smb
     */
    public static void smdDownload(String shareUrl, String localDirectory) {
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(USER_DOMAIN, USER_NAME,
                USER_PWS);
        SmbFile remoteFile = null;
        try {
            remoteFile = new SmbFile(shareUrl, auth);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            if (!remoteFile.exists()) {
                System.out.print("共享文件不存在");
                return;
            }
        } catch (SmbException e) {
            e.printStackTrace();
        }
        // 有文件的时候再初始化输入输出流
        InputStream in = null;
        OutputStream out = null;
        try {
            String fileName = remoteFile.getName();
            File localFile = new File(localDirectory + File.separator + fileName);
            File fileParent = localFile.getParentFile();
            if (null != fileParent && !fileParent.exists()) {
                fileParent.mkdirs();
            }
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buffer = new byte[1024];
            int byteRead;
            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
            out.flush(); //刷新缓冲区输出流
        } catch (Exception e) {
            LoggerUtil.error("", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @Param shareDirectory 共享目录
     * @Param localFilePath 本地目录中的文件路径
     */
    public static void smbUpload(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(new FileInputStream(localFile));
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
            byte[] buffer = new byte[1024];
            int byteRead;
            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行main方法后报了如下错误

jcifs.smb.SmbException
jcifs.util.transport.TransportException
java.io.IOException: Invalid payload size: 405
	at jcifs.smb.SmbTransport.negotiate(SmbTransport.java:279)
	at jcifs.smb.SmbTransport.doConnect(SmbTransport.java:306)
	at jcifs.util.transport.Transport.run(Transport.java:240)
	at java.lang.Thread.run(Thread.java:748)

	at jcifs.util.transport.Transport.run(Transport.java:256)
	at java.lang.Thread.run(Thread.java:748)

	at jcifs.smb.SmbTransport.connect(SmbTransport.java:296)
	at jcifs.smb.SmbTree.treeConnect(SmbTree.java:141)
	at jcifs.smb.SmbFile.doConnect(SmbFile.java:858)
	at jcifs.smb.SmbFile.connect(SmbFile.java:901)
	at jcifs.smb.SmbFile.connect0(SmbFile.java:827)
	at jcifs.smb.SmbFile.exists(SmbFile.java:1360)
	at com.plover.system.util.SmbUtil.listFiles(SmbUtil.java:51)
	at com.plover.system.util.SmbUtil.main(SmbUtil.java:31)

在研究了官方文档搜索了无数论坛后,一直没有找到解决版本,后来在国外某个小论坛有个网友回复降版本可以解决这个问题,于是我把版本替换成1.2.19版本

<dependency>
       <groupId>org.samba.jcifs</groupId>
       <artifactId>jcifs</artifactId>
       <version>1.2.19</version>
</dependency>

完美解决!!

在 Linux 系统下,可以通过 SmbFile 类库来访问 Windows 共享文件夹。SmbFile 是 JCIFS 库的一部分,它提供了一种简单的方式来访问 SMB/CIFS 协议的文件共享。 以下是一个示例代码,演示如何通过 SmbFile 访问 Windows 共享文件夹: ```java import jcifs.smb.SmbFile; public class SmbExample { public static void main(String[] args) { String username = "your_username"; // Windows 用户名 String password = "your_password"; // Windows 密码 String sharedFolder = "smb://192.168.0.100/shared_folder/"; // 共享文件夹路径 String filename = "example.txt"; // 文件名 try { // 创建 SmbFile 对象 SmbFile smbFile = new SmbFile(sharedFolder + filename, username, password); // 读取文件内容 byte[] buffer = new byte[4096]; int bytesRead; try (InputStream inputStream = smbFile.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } System.out.println(outputStream.toString()); } } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们首先创建了一个 SmbFile 对象,然后通过 getInputStream() 方法获取文件的输入流,并读取文件内容。注意,在访问共享文件夹时需要提供 Windows 用户名和密码。 此外,还可以使用 SmbFile 的其他方法来获取文件属性、创建文件夹、上传文件等操作。更多详细信息可以参考 JCIFS 官方文档。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值