Access the server to upload files through JAVA code

The maven environment is used here, which is convenient for importing dependent package
project structure :
insert image description here

pom file :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xunan.study</groupId>
    <artifactId>study-test-project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/jcifs/jcifs -->
        <dependency>
            <groupId>jcifs</groupId>
            <artifactId>jcifs</artifactId>
            <version>1.2.6</version>
        </dependency>

    </dependencies>
</project>

business logic code

package com.xunan.study;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

import jcifs.UniAddress;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import jcifs.smb.SmbSession;

/**
 * 远程共享目录操作 工具类
 * @author wraow
 *
 */
public class SmbFileUtil {
    
    

     /**
     * 方法说明:上传文件到远程共享目录
     * @param localDir         本地临时路径(示例:A:/测试/测试.xls)
     * @param removeDir        远程共享路径(示例:smb://10.169.2.xx/测试/,特殊路径只能用/,smb是协议且必填,也可用http/https)
     * @param removeFileName   远程文件名(示例:测试1.xls)
     * @param removeIp         远程共享目录IP(示例:10.169.2.xx)
     * @param removeLoginUser  远程共享目录用户名(示例:user)
     * @param removeLoginPass  远程共享目录密码(示例:password)
     * @return
     * @throws Exception   0成功/-1失败
     */
    public static void smbUploading(String localDir, String removeDir,String removeFileName,
            String removeIp, String removeLoginUser, String removeLoginPass) throws Exception {
    
    
        NtlmPasswordAuthentication auth = null;
        OutputStream out = null;
        try {
    
    
            //读取本地文件
            File dir = new File(localDir);
            //判断文件是否存在,如果不存在则抛出异常
            if (!dir.exists()) {
    
    
                throw new Exception("本地临时文件不存在!localDir="+localDir);
            }

            //获取IP地址
            InetAddress ip = InetAddress.getByName(removeIp);
            UniAddress address = new UniAddress(ip);
            // 权限验证
            auth = new NtlmPasswordAuthentication(removeIp, removeLoginUser, removeLoginPass);
            SmbSession.logon(address,auth);

            // 拼接上传文件的位置和文件名,   结果示例:文件路径+文件名 = C://user/test.excel
            String remoteFilePath = removeDir + removeFileName;
            //远程路径判断文件文件路径是否合法
            SmbFile remoteFile = new SmbFile(remoteFilePath, auth);
            SmbFile remoteFolder = new SmbFile(removeDir, auth);
            remoteFile.connect();
            //判断remoteFile这个东西是不是一个文件夹(即remoteFilePath这个拼接出来是不是还是一个文件夹),如果是则抛出异常
            if(remoteFile.isDirectory()){
    
    
                throw  new Exception("远程文件路径"+remoteFilePath+"不合法");
            }
            //判断remoteFolder这个文件夹是否存在,存在则跳过,不存在则创建一个
            if(!remoteFolder.exists()){
    
    
                remoteFolder.mkdirs();
            }
            // 向远程共享目录写入本地文件
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
            out.write(toByteArray(dir));
        }  finally{
    
    
            if (out != null) {
    
    
                //关闭流文件
                out.close();
            }
        }
    }
    
    
    /**
     * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
     *
     * @param file 文件
     * @return   字节数组
     * @throws IOException IO异常信息
     */
    public static byte[] toByteArray(File file) throws IOException {
    
    
        FileChannel fc = null;
        try {
    
    
            fc = new RandomAccessFile(file, "r").getChannel();
            MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
                    fc.size()).load();
            byte[] result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
    
    
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
        } finally {
    
    
            if(fc != null){
    
    
                 fc.close();
            }
           
        }
    }

}

Test class :

package com.xunan.study;

public class TestMain {
    
    
    public static void main(String[] args) throws Exception {
    
    
        System.out.println("我执行了");
        //Test.smbUploading();
        SmbFileUtil.smbUploading("","","","","","");
        System.out.println("我结束了");
    }
}

Guess you like

Origin blog.csdn.net/munangs/article/details/131161641