通过smb协议上传下载文件到nas

本文介绍了如何使用Java通过SMB协议操作远程共享目录,包括使用smbj依赖的NasSMBUtil下载和上传文件,以及jcifs库的NasSmbJcifsUtils进行文件操作、目录管理。两种方法展示了在Windows共享文件夹中的不同操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:

需要添加的依赖:

 <!--共享目录文件下载操作工具包-->

<dependency>

    <groupId>com.hierynomus</groupId>

    <artifactId>smbj</artifactId>

    <version>0.10.0</version>

</dependency>
 NasSMBUtil.java 工具类:
package com.cwp.data.application.utils;

import com.cwp.data.application.config.NasFileConfig;
import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.File;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.EnumSet;

/**
 * 远程共享目录操作工具类
 */
@Slf4j
public class NasSMBUtil {

    //private static final String SHARE_DOMAIN = "DOMAIN";

//    private static final String searchPattern_JSON = "*.json";

    private static final String FILE_SEPERATE = "/";


    public static boolean downloadRemoteFileByPathAndConfig(String host, String remoteDir, String filename, String localDestFilePath, NasFileConfig fileConfig) {
        // 设置超时时间(可选)
//        SmbConfig config = SmbConfig.builder()
//                .withTimeout(300, TimeUnit.SECONDS) // Timeout sets Read, Write, and Transact timeouts (default is 60 seconds)
//                .withSoTimeout(300, TimeUnit.SECONDS) // Socket Timeout (default is 0 seconds, blocks forever)
//                .build();

        log.error("fileConfig:{} ,remoteDir:{}", fileConfig, remoteDir);
        String[] dirArr = remoteDir.split(FILE_SEPERATE);
        String rootDir = dirArr[1] + FILE_SEPERATE;
        String secDir = dirArr[2] + FILE_SEPERATE;
        log.info("rootDir:{}, secDir:{}", rootDir, secDir);
        boolean isDownloadSuccess = false;
        try (SMBClient client = new SMBClient()) {
            Connection connection = client.connect(host);
            AuthenticationContext ac = new AuthenticationContext(fileConfig.getAccount(), fileConfig.getPassword().toCharArray(), null);
            Session session = connection.authenticate(ac);
            log.info("共享目录权限认证成功");
            // 连接共享文件夹
            DiskShare share = (DiskShare) session.connectShare(rootDir);
            log.info("进入文件目录:====> {}", rootDir);
            //共享目录图片地址
            String filePath = secDir + filename;
            //需要下载到本地的图片地址
            BufferedOutputStream bos = null;
            InputStream ins = null;
            try {
                bos = new BufferedOutputStream(new FileOutputStream(localDestFilePath));
                log.info("=================开始下载文件: {}", filePath);
                File smbFileRead = share.openFile(filePath, EnumSet.of(AccessMask.GENERIC_READ), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null);
                ins = smbFileRead.getInputStream();
                log.info("smbFileRead inputStream的hashcode:{}", ins.hashCode());
                byte[] buffer = new byte[4096];
                int len;
                while ((len = ins.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
                log.info("==============={} 文件下载成功!", filename);
                isDownloadSuccess = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeStream(bos, ins);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isDownloadSuccess;
    }


    private static void closeStream(BufferedOutputStream bos, InputStream ins) {
        if (null != bos) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != ins) {
            try {
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

 

方式二:

添加依赖:

       <dependency>
            <groupId>jcifs</groupId>
            <artifactId>jcifs</artifactId>
            <version>1.3.17</version>
        </dependency>

工具类:

NasSmbJcifsUtils.java
package cn.getech.data.development.utils;


import cn.getech.data.intelligence.common.exception.RRException;
import jcifs.smb.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.net.UnknownHostException;

/**
 * @ClassName NasSMBUtils
 * @Description TODO
 * @Author Getech
 * @Date 2021/7/6 11:22
 */
@Slf4j
public class NasSmbJcifsUtils {


    private static final String FILE_SEPERATE = "/";


    /**
     * 读取共享文件夹下的所有文件(文件夹)的名称
     * @param remoteUrl
     */
    public static void getSharedFileList(String remoteUrl) {
        SmbFile smbFile;
        try {
            // smb://userName:passWord@host/path/
            smbFile = new SmbFile(remoteUrl);
            if (!smbFile.exists()) {
                System.out.println("no such folder");
            } else {
                SmbFile[] files = smbFile.listFiles();
                for (SmbFile f : files) {
                    System.out.println(f.getName());
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (SmbException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        }
    }

    /**
     * 创建文件夹
     * @param remoteUrl
     * @param folderName
     * @return
     */
    public static void smbMkDir(String remoteUrl, String folderName) {
        SmbFile smbFile;
        try {
            // smb://userName:passWord@host/path/folderName
            smbFile = new SmbFile(remoteUrl + folderName);
            if (!smbFile.exists()) {
                smbFile.mkdir();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     * @param remoteUrl
     * @param shareFolderPath
     * @param localFilePath
     * @param fileName
     */
    public static void uploadFileToSharedFolder(String remoteUrl, String shareFolderPath, String localFilePath, String fileName) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File localFile = new File(localFilePath);
            inputStream = new FileInputStream(localFile);
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            SmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            smbFile.connect();
            outputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 刷新缓冲的输出流
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RRException(e.getMessage());
            }
        }
    }


    /**
     * 上传文件
     * @param remoteUrl
     * @param shareFolderPath
     * @param fileInputStream
     * @param fileName
     */
    public static void uploadFileToSharedFolder(String remoteUrl, String shareFolderPath, InputStream inputStream, String fileName) {
        OutputStream outputStream = null;
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            SmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            smbFile.connect();
            outputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 刷新缓冲的输出流
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
              throw new RRException(e.getMessage());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RRException(e.getMessage());
            }
        }
    }




    /**
     * 下载文件到浏览器
     * @param httpServletResponse
     * @param remoteUrl
     * @param shareFolderPath
     * @param fileName
     */
    public static void downloadFileToBrowser(HttpServletResponse httpServletResponse, String remoteUrl, String shareFolderPath, String fileName) {
        SmbFile smbFile;
        SmbFileInputStream smbFileInputStream = null;
        OutputStream outputStream = null;
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            smbFileInputStream = new SmbFileInputStream(smbFile);
            httpServletResponse.setHeader("content-type", "application/octet-stream");
            httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + fileName);
            // 处理空格转为加号的问题
            httpServletResponse.setHeader("Content-Disposition", "attachment; fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));
            outputStream = httpServletResponse.getOutputStream();
            byte[] buff = new byte[2048];
            int len;
            while ((len = smbFileInputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                outputStream.close();
                smbFileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 下载文件到指定文件夹
     * @param remoteUrl
     * @param shareFolderPath
     * @param fileName
     * @param localDir
     */
    public static void downloadFileToFolder(String remoteUrl, String shareFolderPath, String fileName, String localDir) {
        InputStream in = null;
        OutputStream out = null;
        try {
            SmbFile remoteFile = new SmbFile(remoteUrl + shareFolderPath + File.separator + fileName);
            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();
            }
        }
    }


    /**
     * 删除文件
     * @param remoteUrl
     * @param shareFolderPath
     * @param fileName
     */
    public static void deleteFile(String remoteUrl, String shareFolderPath, String fileName) {
        SmbFile SmbFile;
        try {

            // smb://userName:passWord@host/path/shareFolderPath/fileName
            SmbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            if (SmbFile.exists()) {
                SmbFile.delete();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }

    // (这个方法可以适用比较老版本的windows系统的共享文件夹)
    public static void checkConnect(String host,String username,String password,String remoteUrl) {
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            String url="smb://"+host+remoteUrl;
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);
            SmbFile smbFile = new SmbFile(url,auth);
            System.out.println("smburl="+url);
            SmbFile[] files = smbFile.listFiles();
            for (SmbFile f : files) {
                    System.out.println(f.getName());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (SmbException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        }
    }


    /**
    * @Description 上传文件到nas文件夹 (这个方法可以适用比较老版本的windows系统的共享文件夹)
    * @Author  chengweiping
    * @Date   2021/7/23 12:22
    */
    public static void uploadFileToSharedFolder(String host,String dir,String fileName,String username,String password,InputStream inputStream) {
        OutputStream outputStream = null;
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
           //  SmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            System.out.println("host:"+host+";password:"+password+";dir:"+dir+"fileName:"+fileName);
            String url="smb://"+host+dir;
            String fileNameUrl=url+fileName;
            System.out.println("url:"+url);
            System.out.println("fileNameUrl:"+fileNameUrl);
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);
            SmbFile smbFile = new SmbFile(fileNameUrl,auth);
            outputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 刷新缓冲的输出流
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } finally {
            try {
                if(outputStream!=null){
                    outputStream.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }


            } catch (IOException e) {
                e.printStackTrace();
                throw new RRException(e.getMessage());
            }
        }
    }

    // smb://Getech:6661262@10.88.40.102/poc_202105
    private static final String SMB_SHARE_FOLDER = "smb://Getech:6661262@10.88.40.225:80/poc_202105/";
    private static final String SHARE_FOLDER_PATH = "/dip_data_service";
    private static final String FILE_NAME = "test3.txt";
    private static final String LOCAL_DIR = "D:\\LocalTest\\test.txt";

    public static void main(String[] args) {
        //uploadFileToSharedFolder(SMB_SHARE_FOLDER,SHARE_FOLDER_PATH,LOCAL_DIR,FILE_NAME);
     //   getSharedFileList(SMB_SHARE_FOLDER+SHARE_FOLDER_PATH+"/");
        String host= "10.88.40.225";
        String remoteDir= "/poc_202105/";
        String username="getech";
        String password="6661262";
        String port= "80";
        System.out.println("host:="+host+";port:"+port+",username:"+username+",password="+password+",dir="+remoteDir);
        checkConnect(host,username,password,remoteDir);
    }



}

 

 

参考文章链接:

Java中SMB的应用_终极冥帝-优快云博客_java smb

 

rancher搭建samda服务教程

优快云https://mp.youkuaiyun.com/mp_blog/creation/editor/12211095

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

成伟平2022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值