利用SMB jcifs實現對windows中的共享文件夾的操作


需求是在本地上傳文件到服務器上,服務器是windows的,使用共享文件夾提供權限給你的。

利用第三方:

  CIFS (Common Internet File System) 

  SMB(Server Message Block)

  CIFS是公共的或開放的SMB協議版本,並由Microsoft使用。SMB協議(見最后的名詞解釋)現在是局域網上用於服務器文件訪問和打印的協議。象SMB協議一樣,CIFS在高層運行,而不象TCP/IP協議那樣運行在底層。CIFS可以看做是應用程序協議如文件傳輸協議和超文本傳輸協議的一個實現。

  作用:

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

  1.訪問服務器本地文件並讀寫這些文件 

  2.與其它用戶一起共享一些文件塊 

  3.在斷線時自動恢復與網絡的連接 

  4.使用西歐字符文件名 

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","123456");
            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 = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++){
            XSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null){
                continue;
            }
            ArrayList<Resource> resources = new ArrayList<Resource>();

            //讀取每一行, 第一行為標題行跳過
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++){
                XSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow == null){
                    continue;
                }

                //我們只讀取指定的CFN三列的數據
                Resource resource = new Resource();
                resource.setTaskNo(hssfRow.getCell(2).getStringCellValue());
                resource.setActiveIngredient(hssfRow.getCell(5).getStringCellValue());
                String applicationNo = hssfRow.getCell(13).getStringCellValue();
                //去掉結尾的.數字
                applicationNo = applicationNo.substring(0, 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.19</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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM