摘要 使用Java通过JCIFS框架读写共享文件夹,使用SMB协议,并支持域认证。

项目常常需要有访问共享文件夹的需求,例如读取共享文件夹存储的视频、照片和PPT等文件。那么如何使用Java读写Windows共享文件夹呢?

使用Java访问拥有全部读写权限的共享文件夹比较简单,和普通的目录没有什么区别。但是,如果从Linux服务器访问一个windows服务器上需要用户名和密码验证的共享文件夹,就需要一点点小技巧了。这里介绍一个开源的库JCIFS,他可以轻松满足此需求。

JCIFS是使用Java语言开发的一款开源框架,通过SMB协议访问远程共享文件夹,就像访问本地文件夹一样,简简单单。她同时支持Windows和Linux共享文件夹,不过,Linux共享文件夹需要安装Samba服务软件(官网:http://www.samba.org/)。

另外,通过挂载该共享文件夹到Linux服务器下也可以实现,此时不需要借助SMB协议,对此,这里不做介绍,感兴趣的童鞋可以去问问度娘。

言归正传,maven依赖如下:

<!-- https://mvnrepository.com/artifact/org.samba.jcifs/jcifs -->
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.3</version>
</dependency>

SMB(Server Message Block)通信协议是微软(Microsoft)和英特尔(Intel)在1987年制定的协议,主要是作为Microsoft网络的通讯协议。SMB 是在会话层(session layer)和表示层(presentation layer)以及小部分应用层(application layer)的协议。通过设置“NetBIOS over TCP/IP”使得Samba不但能与局域网络主机分享资源,还能与全世界的电脑分享资源。

代码示例:

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://132.20.2.33/CIMPublicTest/】
// 目录
String shareDir = "smb:// 132.20.2.33/CIMPublicTest/";
listFiles(shareDir); } /**
* @Title listFiles
* @Description 遍历指定目录下的文件
* @date 2019-01-11 09:56
*/
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, 第二个是用户名,第三个是密码。下面列举SMB协议的两个应用场景。SmbFile类和Java的File类十分相似,使用其对象可以处理远程共享文件的读写。

    /**
* @Title smbGet
* @Param shareUrl 共享目录中的文件路径,如smb://132.20.2.33/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 本地目录中的文件路径
* @date 2019-01-10 20:16
*/
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();
}
}
}

在Java程序中读写windows共享文件夹的更多相关文章

  1. Java读写Windows共享文件夹 .

    版权声明:本文为博主原创文章,未经博主允许不得转载. 项目常常需要有访问共享文件夹的需求,例如共享文件夹存储照片.文件等.那么如何使用Java读写Windows共享文件夹呢? Java可以使用JCIF ...

  2. 在java程序中访问windows有用户名和密码保护的共享目录

    在java程序中访问windows有用户名和密码保护的共享目录 Posted on 2015-11-20 14:03 云自无心水自闲 阅读(3744) 评论(0)  编辑  收藏 --> Jav ...

  3. CentOS中设置Windows共享文件夹

    在CentOS中设置Samba可实现和Windows共享文件夹.常见的需求:1)用户能够在Windows机器上通过共享文件夹访问远程Linux服务器上自己的主目录:2)用户能够在Windows机器上访 ...

  4. Mac OS访问Windows共享文件夹

    原文地址:http://blog.csdn.net/jinhill/article/details/7246922 最近开始研究Mac OS,遇到的第一个问题就是如何在Mac OS中访问Windows ...

  5. 烂泥:CentOS6.5挂载windows共享文件夹

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 由于工作需要,需要把本机的文件夹共享出去,然后让CentOS服务器临时使用下. 服务器使用的是CentOS系统,而本机使用的win7系统.考虑到是临时使 ...

  6. linux上挂载windows共享文件夹

    linux上挂载windows共享文件夹 1.共享windows目录 挂载之前得创建一个有password的用户(当前用户也能够),并将你要挂载的目录进行共享,并赋予读写权限 如图. watermar ...

  7. windows共享文件夹如何让CentOS 6.5读取

    http://www.111cn.net/sys/CentOS/74104.htm 工作需要,需要把本地win7共享的文件夹让CenotOS 6.5服务器临时使用一下,以下是CentOS 6.5系统挂 ...

  8. 在Linux下访问Windows共享文件夹

    说明 以下操作以Ubuntu为例,大家可以参考. 我在Ubuntu 14.04和16.04都试过了. Windows共享文件夹 如果局域网内有一台Windows主机,将指定文件夹设为共享,就可以在局域 ...

  9. Linux上从Java程序中调用C函数

    原则上来说,"100%纯Java"的解决方法是最好的,但有些情况下必须使用本地方法.特别是在以下三种情况: 需要访问Java平台无法访问的系统特性和设备: 通过基准测试,发现Jav ...

随机推荐

  1. InstrumentDriver,对iOS自动化测试说 Yes!

    InstrumentDriver 是 Mobile自动化小组最近实现的基于 instrument,针对 iOS 的自动化测试框架,目前支持 java 语言编写测试用例. 研究过iOS自动化测试的同学肯 ...

  2. Fixed Partition Memory Management UVALive - 2238 建图很巧妙 km算法左右顶点个数不等模板以及需要注意的问题 求最小权匹配

    /** 题目: Fixed Partition Memory Management UVALive - 2238 链接:https://vjudge.net/problem/UVALive-2238 ...

  3. http://www.cnblogs.com/chenmeng0818/p/6370819.html

    http://www.cnblogs.com/chenmeng0818/p/6370819.html js中的正则表达式入门   什么是正则表达式呢? 正则表达式(regular expression ...

  4. js实现选中文字 分享功能

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  5. 【问题集】redis集群set报错(error) MOVED 11469 192.168.181.201:7002

    没有启动集群模式(即缺少了那个"-c"): redis-cli -c -h yourhost -p yourpost

  6. Spring.NET依赖注入框架学习--实例化容器常用方法

    Spring.NET依赖注入框架学习---实例化容器常用方法 本篇学习实例化Spring.NET容器的俩种方式 1.通过XmlObjectFactory创建一个Spring.NET容器 IResour ...

  7. Elasticsearch 学习之不停止服务,完成升级重启维护操作

    我们可以设置集群的平衡参数来暂时禁用掉平衡,具体步骤如下: 1.如果可能的话,先暂停掉数据新增和更新操作,这样会提高集群恢复的时间: 2.禁用集群分片平衡操作,直到告诉集群可以恢复平衡操作为止,禁用配 ...

  8. 搞懂MapReduce

    MapReduce的主要思想就是将计算任务分发至多台计算机(slave),然后master综合计算机结果.所以就涉及到多台计算机通信和同步的问题,这个应该由hadoop完成,把环境配置好后就像单机操作 ...

  9. Springmvc的原理和业务处理

    要尽量弄懂这个springmvc的工作原理:DispatcherServle,HandlerMapping,HandlerAdapter和ViewResolver等对象协同工作,完成springmvc ...

  10. DOM常用事件绑定方式与实例

    一.常用的事件 onclick 点击事件 模态框实例 <input type="button" id="b1" style="width:50p ...