行业知识
使用Java局域网读取windows共享文件夹(smb协议)
2026-12-04 10:27:17
来源:互联网转载
文章目录
- 前言
- 一、smb协议简单了解
- 二、demo
- 1.设置文件夹为共享文件夹
- 2.Java代码
- 总结
前言
使用Java局域网读取windows共享文件夹(smb协议)
一、smb协议简单了解
SMB(全称是Server Message Block)是一个网络协议名,它能被用于Web连接和客户端与服务器之间的信息沟通。SMB最初是IBM的贝瑞·费根鲍姆(Barry Feigenbaum)研制的,其目的是将DOS操作系统中的本地文件接口“中断13”改造为网络文件系统。
二、demo
1.设置文件夹为共享文件夹
(1)右键文件夹点击属性
(2)点击共享
(3)添加everyone 点击共享
(4)点击网络共享中心配置
(4)另一台局域网电脑怎么访问共享的文件夹。
2.Java代码
(1)用到的Maven依赖
jcifs jcifs 1.3.17
(2)获取共享文件夹下所有的文件
/** * 读取共享文件夹下的所有文件(文件夹)的名称 * * @param "smb://192.168.1.215/ecg/2022-09-29/ */ public static SmbFile[] getSharedFileList(String smbFileUrl) { SmbFile smbFile; try { smbFile = new SmbFile(smbFileUrl); if (!smbFile.exists()) { log.error("文件夹不存在"); } else { SmbFile[] files = smbFile.listFiles(); return files; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SmbException e) { e.printStackTrace(); } return null; }(2)下载文件到指定文件夹
/** * 下载文件到指定文件夹 * @param remoteUrl 远程文件夹路径 * @param fileName 文件名称 * @param localDir 要下载到本地的路径 * @param localFileName 下载到本地的文件重命名名称 */ public static void downloadFileToFolder(String remoteUrl, String fileName, String localDir, String localFileName) { InputStream in = null; OutputStream out = null; try { File dir = new File(localDir); if(!dir.exists()){ dir.mkdir(); } SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName); File localFile = new File(localDir + "/" + localFileName); 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(); } } }总结
注意要处与同一局域网内