利用SMB jcifs实现对windows中的共享文件夹的操作

时间:2021-07-06 15:29:05

需求是在本地上传文件到服务器上,服务器是windows的,使用共享文件夹提供权限给你的。

利用第三方:

  CIFS (Common Internet File System)

  SMB(Server Message Block)

  CIFS是公共的或开放的SMB协议版本,并由Microsoft使用。SMB协议(见最后的名词解释)现在是局域网上用于服务器文件访问和打印的协议。象SMB协议一样,CIFS在高层运行,而不象TCP/IP协议那样运行在底层。CIFS可以看做是应用程序协议如文件传输协议和超文本传输协议的一个实现。

  作用:

 CIFS 可以使您达到以下功能: 

  .访问服务器本地文件并读写这些文件 

  .与其它用户一起共享一些文件块 

  .在断线时自动恢复与网络的连接 

  .使用西欧字符文件名 

JCIFS的开发方法类似java的文件操作功能,它的资源url定位:smb://{user}:{password}@{host}/{path},smb为协议名,user和password分别为共享文件机子的登陆名和密码,@后面是要访问的资源的主机名或IP地址

  我的经验是将SMBFile当成普通File操作

  例子:

package com.zhen;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* @author zhen
* @Date 2018/5/25 15:47
*/
public class UploadFile { //协议是smb,格式按照指定格式 这里不正确报过协议错误
private String basePath = "smb://guozhen:123456@10.15.35.211/test_guo"; /**
* 向共享目录上传文件
* @param remoteUrl
* @param localFilePath
*/
public void uploadFile(String remoteUrl, String localFilePath) {
try {
File localFile = new File(localFilePath);
String fileName = localFile.getName();
//权限, 刚开始没有验证权限报过错误
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://10.15.35.211","guozhen","");
SmbFile file = new SmbFile(remoteUrl, auth);
//当成file用
if (!file.exists()){
file.mkdirs();
}
//下面一行本来打算想新建File在指定目录下并且指定文件名,后面发现第一个参数与File同方法参数意义不同
SmbFile remoteFile = new SmbFile( file.getURL() + "/" + fileName);
IOUtils.copy(new FileInputStream(localFile), new SmbFileOutputStream(remoteFile));
} catch (Exception e) {
e.printStackTrace();
}
} public String getSavePath(String fileName) throws Exception{
String applicationNo = ""; Pattern pattern = Pattern.compile("[0-9]+");// 匹配的模式
Matcher m = pattern.matcher(fileName);
m.find();
applicationNo = m.group(); File db = new File("src/main/java/com/zhen/resourceMapper.xml");
Document document = new SAXReader().read(db);
Element resourceElement = (Element)document.selectSingleNode("//resource[@applicationNo='" + applicationNo + "']"); String taskNo = resourceElement.attributeValue("taskNo");
String activeIngredient = resourceElement.attributeValue("activeIngredient");
String applicationNo1 = resourceElement.attributeValue("applicationNo"); return taskNo + " " + activeIngredient + " " + applicationNo1;
} /**
* 上传资源文件
*/
public void uploadResource(String filePath) throws Exception{
File file = new File(filePath);
if (file.isFile()){
uploadFile(basePath + "/" + getSavePath(file.getName()), filePath);
}else if(file.isDirectory()){
File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
if (files != null) {
for (File f : files) {
if (f.isFile()) {
uploadResource(f.getAbsolutePath());
} else if (f.isDirectory()) {
uploadResource(f.getAbsolutePath());
}
}
}
} } /**
* 读取资源目录
*/
public void readResourceList(String filePath) throws Exception{
//读取xlsx文件
XSSFWorkbook hssfWorkbook = null;
//寻找目录读取文件
File excelFile = new File(filePath);
hssfWorkbook = new XSSFWorkbook(new FileInputStream(excelFile));
if (hssfWorkbook == null){
System.out.println("路径有误");
return;
} for(int numSheet = ; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++){
XSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null){
continue;
}
ArrayList<Resource> resources = new ArrayList<Resource>(); //读取每一行, 第一行为标题行跳过
for (int rowNum = ; rowNum <= hssfSheet.getLastRowNum(); rowNum++){
XSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null){
continue;
} //我们只读取指定的CFN三列的数据
Resource resource = new Resource();
resource.setTaskNo(hssfRow.getCell().getStringCellValue());
resource.setActiveIngredient(hssfRow.getCell().getStringCellValue());
String applicationNo = hssfRow.getCell().getStringCellValue();
//去掉结尾的.数字
applicationNo = applicationNo.substring(, applicationNo.lastIndexOf("."));
//去掉开头的CN等,编号是数字
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(applicationNo);
matcher.find();
applicationNo = matcher.group();
resource.setApplicationNo(applicationNo);
resources.add(resource);
} writeResource(resources);
}
} public void writeResource(List<Resource> resources) throws Exception{
File db = new File("src/main/java/com/zhen/resourceMapper.xml");
Document document = new SAXReader().read(db); for (Resource resource : resources) {
Node resourceElement = document.selectSingleNode("//resource"
+ "[@applicationNo='" + resource.getApplicationNo() + "'"
+ " and @taskNo='" +resource.getTaskNo() + "'"
+ " and @activeIngredient='" + resource.getActiveIngredient() + "']");
if (resourceElement == null){
//创建节点
Element root = document.getRootElement();
//往根节点添加resource元素
Element resourceElement1 = root.addElement("resource");
//设置user的userID
resourceElement1.addAttribute("taskNo", resource.getTaskNo());
resourceElement1.addAttribute("applicationNo", resource.getApplicationNo());
resourceElement1.addAttribute("activeIngredient", resource.getActiveIngredient());
write(document);
}
} } public void write(Document document) throws Exception {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(
new OutputStreamWriter(
new FileOutputStream(new File("src/main/java/com/zhen/resourceMapper.xml")),"UTF-8")
,format);
writer.write(document);
writer.flush();
writer.close();
} public static void main(String[] args) throws Exception{
UploadFile uploadFile1 = new UploadFile();
// uploadFile1.readResourceList("C:\\Users\\zhen\\Desktop\\work\\resource\\工作簿1.xlsx");
uploadFile1.uploadResource("C:\\Users\\zhen\\Desktop\\work\\ss");
} }

导入的有关jar:

     <dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.2.</version>
</dependency>

更多以后用到再更新。

参考链接:

https://blog.csdn.net/z69183787/article/details/14161109

https://blog.csdn.net/xwq911/article/details/49738111

https://bbs.csdn.net/topics/391990197?page=1

https://bbs.csdn.net/topics/380139145