如何使用Java代码读写windows共享文件夹呢?

乔欣 Java经验 发布时间:2023-02-16 21:23:29 阅读数:2896 1
下文笔者讲述使用java代码读写windows共享文件夹的方法分享,如下所示

Java读写windows共享文件夹的实现思路

借助JCIFS框架读写共享文件夹
     (使用SMB协议
	  此方式支持域认证)

JCIFS简介

 JCIFS是
    使用Java语言开发的一款开源框架
    通过SMB协议访问远程共享文件夹
    就像访问本地文件夹一样
    JCIFS同时支持Windows和Linux共享文件夹
注意事项:
     Linux共享文件夹需要安装Samba服务软件(官网:http://www.samba.org/)
例:
java代码访问共享文件夹的示例
   1.引入依赖
<!-- https://mvnrepository.com/artifact/org.samba.jcifs/jcifs -->
<dependency>
    <groupId>org.samba.jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.3</version>
</dependency>


//2.编写相应的代码

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class SmbFileUtil {

    private static Logger log = LoggerFactory.getLogger(SmbFileUtil.class);

    private static String USER_DOMAIN = "yourDomain";
    private static String USER_ACCOUNT = "yourAccount";
    private static String USER_PWS = "yourPassword";

    public static void main(String[] args) throws Exception {

        // remoteUrl 格式示例 【smb://8.8.8.8/CIMPublicTest/】
        // 目录
        String shareDir = "smb://8.8.8.8/CIMPublicTest/";
        listFiles(shareDir);
        
    }

    /**
     * @Title listFiles
     * @Description 遍历指定目录下的文件 
     */
    private static void listFiles(String shareDirectory) throws Exception {
        long startTime = System.currentTimeMillis();

        // 域服务器验证
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(USER_DOMAIN, USER_ACCOUNT,
                USER_PWS);
        SmbFile remoteFile = new SmbFile(shareDirectory, auth);
        log.info("远程共享目录访问耗时:【{}】", System.currentTimeMillis() - startTime);

        if (remotefile.exists()) {
            SmbFile[] files = remoteFile.listFiles();
            remoteFile.listFiles(shareDirectory);
            
            for (SmbFile f : files) {
                log.info(f.getName());
            }
        } else {
            log.info("文件不存在");
        }
    }
}

/*
NtlmPasswordAuthentication类用于域认证
    需要三个参数
      第一个是域名,如果没有,就赋值null,
      第二个是用户名
      第三个是密码
*/
 
/**
 * @Title smbGet
 * @Param shareUrl 共享目录中的文件路径,如smb://8.8.8.8/CIMPublicTest/eg.txt
 * @Param localDirectory 本地目录,如tempStore/smb
 */
public static void smbGet(String shareUrl, String localDirectory) throws Exception {
	NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(USER_DOMAIN, USER_ACCOUNT,
			USER_PWS);
	SmbFile remoteFile = new SmbFile(shareUrl, auth);
	if (!remoteFile.exists()) {
		log.info("共享文件不存在");
		return;
	}
	// 有文件的时候再初始化输入输出流
	InputStream in = null;
	OutputStream out = null;
	log.info("下载共享目录的文件 shareUrl 到 localDirectory");
	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];
		while (in.read(buffer) != -1) {
			out.write(buffer);
			buffer = new byte[1024];
		}
		out.flush(); //刷新缓冲区输出流

	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		out.close();
		in.close();
	}
}

/**
 * 
 * @Title smbPut
 * @Description 向共享目录上传文件
 * @Param shareDirectory 共享目录
 * @Param localFilePath 本地目录中的文件路径 
 */
public static void smbPut(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];
		while (in.read(buffer) != -1) {
			out.write(buffer);
			buffer = new byte[1024];
		}
		out.flush();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202302/16765538555814.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者