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

    @Autowired
    private 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功能

通过后台日志打印,可以清楚的看到链接,登录以及获取权限等操作信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值