文件传输服务应用1——java集成smb2/3实现文件共享方案详细教程和windows共享服务使用配置

本文主要是介绍文件传输服务应用1——java集成smb2/3实现文件共享方案详细教程和windows共享服务使用配置,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在实际项目开发过程中,读取网络资源或者局域网内主机的文件是必要的操作和需求。而FTP(文件传输协议)和SMB(服务器消息块)是两种最为常见的文件传输协议。它们各自在文件传输领域拥有独特的优势和特点,但同时也存在一些差异。

本文以java集成smb为案例说明,其中SMB作为一种在Windows环境中广泛使用的文件共享协议,特别适合于局域网内的文件共享和协作,具体如何集成开发请详细阅读。

本文案以springboot2.1.5作为开发对象。

一.设置共享文件夹,也就是smb服务(以windows为测试对象)

1.首先在我的电脑下,找C盘之外的盘符新建一个文件夹,本例以SMB_Server做介绍

2.然后就可以用网络路径在局域网内的浏览器或者我的电脑访问共享的文件。

注意:

可以使用ip或者域来访问,其中域指的是smb服务电脑的设备名称(在我的电脑属性查看)

3.开启smb服务后,如果不能正常访问请查看以下网站处理

https://learn.microsoft.com/zh-CN/troubleshoot/windows-server/networking/dns-cname-alias-cannot-access-smb-file-server-share

二.java项目引入smb共享文件包

需要注意的是:

使用smb作为传输协议时,其存在协议版本的问题,需要同时引入smb1和smb2/3才能正常工作。

        <!--SMB共享文件--><!-- https://mvnrepository.com/artifact/jcifs/jcifs --><!--smb1--><dependency><groupId>jcifs</groupId><artifactId>jcifs</artifactId><version>1.3.17</version></dependency><!--smb2/3--><dependency><groupId>com.hierynomus</groupId><artifactId>smbj</artifactId><version>0.11.3</version></dependency>

三.配置smb链接信息,构造java链接使用工具

1.新增smb-config.properties配置文件
##########################
# SMB配置信息
##################################### ———以下是Windows本地服务配置信息
smb.hostname=127.0.0.1
## 域名,没有可以为空
smb.domain=wp-pc
smb.username=wp
smb.password=123456
## 一定记得是共享目录名称,其他无须添加
smb.server.root=SMB_Server
## 需要访问的目录名称,后缀必须带"/"
smb.server.path=/project/opt/
## 本地存放SMB下载的结果文件的目录
smb.local.path=D:\\test\\project\\opt\\
# 本地存放运行对接需要的数据
smb.local.rundata=D:\\data\\rundata\\############## ———以下是linux服务器配置信息
#smb.hostname=10.1.0.21
#smb.domain=
#smb.username=root
#smb.password=root
#smb.server.root=SMB_Server
#smb.server.path=/project/opt/
#smb.local.path=/root/demo/project/opt/
#smb.local.rundata=/root/demo/project/rundata/
@lombok.Data
@Component
/*** 加载SMB自定义配置文件* 配置文件需放在resources文件夹根目录*/
@PropertySource("classpath:smb-config.properties")
public class SMBConfigInfo {@Value("${smb.hostname}")private String hostname;@Value("${smb.domain}")private String domain;@Value("${smb.username}")private String username;@Value("${smb.password}")private String password;@Value("${smb.server.root}")private String rootPath;@Value("${smb.server.path}")private String serverPath;@Value("${smb.local.rundata}")private String runDataPath;
}
 2.新增SMB共享文件工具,可支持登录,读取,下载,上传等操作
/*** SMB共享文件工具* 支持登录,读取,下载,上传等操作* @author wp*/
@Component
public class SMBUtils {@Autowiredprivate SMBConfigInfo smbConfigInfo;/*** 登录SMB服务** @return*/private NtlmPasswordAuthentication loginSMBServer() {UniAddress dc;NtlmPasswordAuthentication authentication = null;try {dc = UniAddress.getByName(smbConfigInfo.getHostname());authentication = new NtlmPasswordAuthentication(smbConfigInfo.getDomain(), smbConfigInfo.getUsername(), smbConfigInfo.getPassword());SmbSession.logon(dc, authentication);} catch (Exception e) {e.printStackTrace();System.out.println("loginSMBServer fail:" + smbConfigInfo.toString());return null;}return authentication;}/*** 从SMB服务器下载文件到本地路径* 路径格式:smb://192.168.1.21/test/新建文本文档.txt* smb://username:password@192.168.1.21/test** @param remoteUrl 远程路径* @param localDir  要写入的本地路径*/public void getSMBFileByDown(String remoteUrl, String localDir) {InputStream in = null;OutputStream out = null;NtlmPasswordAuthentication auth = loginSMBServer();if (auth == null) {return;}try {SmbFile remoteFile = new SmbFile(remoteUrl, auth);if (!remoteFile.isFile()) {System.out.println("共享文件不存在");return;}String fileName = remoteFile.getName();File fileDir = new File(localDir);if (!fileDir.exists()) {fileDir.mkdirs();}File localFile = new File(localDir + File.separator + fileName);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();}}}/*** 通过读取SMB远程文件获得输入流* 如果输入流在别处使用的时候,一定记得不要先关闭* 另外流不能直接上传或者操作,否则有异常* 须先下载到本地,然后再处理** @param remoteUrl* @return*/public InputStream getInputStreamBySMBFile(String remoteUrl) {NtlmPasswordAuthentication auth = loginSMBServer();if (auth == null) {return null;}InputStream in = null;try {SmbFile remoteFile = new SmbFile(remoteUrl, auth);if (!remoteFile.isFile()) {System.out.println("共享文件不存在");return in;}in = new BufferedInputStream(new SmbFileInputStream(remoteFile));byte[] buffer = new byte[1024];while (in.read(buffer) != -1) {buffer = new byte[1024];}} catch (Exception e) {e.printStackTrace();} finally {/*try {in.close();} catch (IOException e) {e.printStackTrace();}*/}return in;}/*** 从本地上传文件到指定SMB指定目录** @param remoteUrl     文件的全路径+文件名称* @param localFilePath*/public void getSMBFileByUpload(String remoteUrl, String localFilePath) {NtlmPasswordAuthentication auth = loginSMBServer();if (auth == null) {return;}InputStream in = null;OutputStream out = null;try {File localFile = new File(localFilePath);String fileName = localFile.getName();SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName, auth);if (!remoteFile.exists()) {remoteFile.createNewFile();}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];}} catch (Exception e) {e.printStackTrace();} finally {try {out.close();in.close();} catch (IOException e) {e.printStackTrace();}}}/*** 读取SMB服务指定目录的文件* smb://administrator:dibindb@10.1.1.12/share/aa.txt** @param remoteUrl* @param fileName* @return*/public String readSMBFile(String remoteUrl, String fileName) {NtlmPasswordAuthentication auth = loginSMBServer();if (auth == null) {return "";}SmbFileInputStream smbIn = null;StringBuffer strBu = new StringBuffer();try {SmbFile smbCatalog = new SmbFile(remoteUrl, auth);if (!smbCatalog.exists()) {smbCatalog.mkdirs();}SmbFile smbFile = new SmbFile(remoteUrl + fileName, auth);if (!smbFile.isFile()) {smbFile.createNewFile();}// 得到文件的大小int length = smbFile.getContentLength();byte buffer[] = new byte[ConstantDataList.SYSTEM_BUFFER_SIZE];// 建立smb文件输入流smbIn = new SmbFileInputStream(smbFile);int leng = -1;while ((leng = smbIn.read(buffer)) != -1) {strBu.append(new String(buffer, 0, leng));}} catch (Exception e) {e.printStackTrace();} finally {try {smbIn.close();} catch (IOException e) {e.printStackTrace();}}return strBu.toString();}/*** 将jsonStr写入SMB指定的目录文件中** @param remoteUrl* @param fileName* @param jsonStr*/public void writeSMBFile(String remoteUrl, String fileName,String jsonStr) {NtlmPasswordAuthentication auth = loginSMBServer();if (auth == null) {return;}//将str转化成输入流ByteArrayInputStream smbIn = new ByteArrayInputStream(jsonStr.getBytes());SmbFileOutputStream out = null;try {SmbFile smbCatalog = new SmbFile(remoteUrl, auth);if (!smbCatalog.exists()) {smbCatalog.mkdirs();}SmbFile smbFile = new SmbFile(remoteUrl + fileName, auth);if (!smbFile.isFile()) {smbFile.createNewFile();}out = new SmbFileOutputStream(smbFile);// 得到文件的大小byte buffer[] = new byte[4096];int leng = -1;while ((leng = smbIn.read(buffer)) != -1) {out.write(buffer, 0, leng);}out.flush();} catch (Exception e) {e.printStackTrace();} finally {try {smbIn.close();out.close();} catch (IOException e) {e.printStackTrace();}}}}

 四.测试java链接操作smb功能

通过后台日志打印,可以清楚的看到链接,登录以及获取权限等操作信息

这篇关于文件传输服务应用1——java集成smb2/3实现文件共享方案详细教程和windows共享服务使用配置的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1002040

相关文章

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

Windows系统宽带限制如何解除?

《Windows系统宽带限制如何解除?》有不少用户反映电脑网速慢得情况,可能是宽带速度被限制的原因,只需解除限制即可,具体该如何操作呢?本文就跟大家一起来看看Windows系统解除网络限制的操作方法吧... 有不少用户反映电脑网速慢得情况,可能是宽带速度被限制的原因,只需解除限制即可,具体该如何操作呢?本文

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

电脑找不到mfc90u.dll文件怎么办? 系统报错mfc90u.dll丢失修复的5种方案

《电脑找不到mfc90u.dll文件怎么办?系统报错mfc90u.dll丢失修复的5种方案》在我们日常使用电脑的过程中,可能会遇到一些软件或系统错误,其中之一就是mfc90u.dll丢失,那么,mf... 在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包