文件传输服务应用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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——