Java-FTPサーバーファイルのアップロードとダウンロードを実現

10929 ワード

目次
1、pom.xml
2、プロファイル
3、工具類
4、使用
1、pom.xml

	com.jcraft
	jsch
	0.1.54


2、プロファイル
sftp:
  ftp_address: ${back.address}
  ftp_port: ${back.port}
  ftp_username: ${back.username}
  ftp_password: ${back.password}

3、工具類
import com.jcraft.jsch.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.Vector;

@Slf4j
@Component
@Data
public class SFTPUtil {


    private Session session = null;
    private ChannelSftp channel = null;
    private int timeout = 60000;

    /**
     *  CST              
     *
     * @param str
     * @return
     */
    public static String CSTFormat(String str) {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date date = null;
        try {
            date = (Date) formatter.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     *   sftp   
     *
     * @throws JSchException
     */
    public void connect(String ftpUsername,String ftpAddress,int ftpPort,String ftpPassword) throws JSchException {
        if (channel != null) {
            System.out.println("channel is not null");
        }
        //  JSch  
        JSch jSch = new JSch();
        //     ,  ip       Session  
        session = jSch.getSession(ftpUsername, ftpAddress, ftpPort);
        //    
        session.setPassword(ftpPassword);
        System.out.println("Session created.");
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // Session    properties
        session.setConfig(config);
        //    
        session.setTimeout(timeout);
        //  Session    
        session.connect();
        System.out.println("Session connected.");
        //   SFTP  
        channel = (ChannelSftp) session.openChannel("sftp");
        //   SFTP     
        channel.connect();
        System.out.println("Opening Channel.");
    }

    /**
     *     
     *
     * @param src linux       
     * @param dst       
     * @throws JSchException
     * @throws SftpException
     */
    public void download(String src, FileOutputStream dst) throws SftpException {
        channel.get(src, dst);
        channel.quit();
    }

    /**
     *     
     *
     * @param src      
     * @param dst      , dst   ,        src     。
     *                     :OVERWRITE
     * @throws JSchException
     * @throws SftpException
     */

    public void upLoadPath(String src, String dst) throws SftpException {
        createDir(dst);
        channel.put(src, dst);
        channel.quit();
    }

    /**
     *     
     *
     * @param src         input stream  
     * @param dst            
     * @param fileName      
     *                          :OVERWRITE
     * @throws JSchException
     * @throws SftpException
     */
    public void upLoadFile(InputStream src, String dst, String fileName) throws SftpException {
        createDir(dst);
        channel.put(src, fileName);
        channel.quit();
    }
    /**
     *     
     */
    public void deleteFile(String directory,String deleteFile) throws SftpException {
        try {
            channel.cd(directory);
        } catch (SftpException e) {
            e.printStackTrace();
        }
        try {
            channel.rm(deleteFile);
        } catch (SftpException e) {
            e.printStackTrace();
        }
        channel.quit();
    }
    /**
     *         
     */
    public void createDir(String createPath) throws SftpException {

        if (isDirExist(createPath)) {
            channel.cd(createPath);
            return;
        }
        String pathArry[] = createPath.split("/");
        StringBuffer filePath = new StringBuffer("/");
        for (String path : pathArry) {
            if (path.equals("")) {
                continue;
            }
            filePath.append(path + "/");
            if (isDirExist(filePath.toString())) {
                channel.cd(filePath.toString());
            } else {
                //     
                channel.mkdir(filePath.toString());
                //           
                channel.cd(filePath.toString());
            }
        }
        channel.cd(createPath);
    }

    /**
     *         
     */
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = channel.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     *           
     *
     * @param oldPath
     * @param newPath
     * @throws SftpException
     */
    public void rename(String oldPath, String newPath) throws SftpException {
        channel.rename(oldPath, newPath);
    }

    /**
     *                 。
     *
     * @param path
     * @return
     * @throws SftpException
     */
    public Vector ls(String path) throws SftpException {
        Vector vector = channel.ls(path);
        return vector;
    }

    /**
     *     
     */
    public void close() {
        //     ,           
        if (channel != null && channel.isConnected()) {
            channel.disconnect();
        }

        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }
}

tips:Jschには,(1)OVERWRITE:フルオーバーライドモードの3種類のファイル転送モードがある.Jschのデフォルトファイル転送モードでは、転送されたファイルがターゲットファイルを上書きします.(2)APPEND:追加モード.ターゲットファイルが既に存在する場合は、ターゲットファイルの後に追加します.(3)RESUME:復帰モード.ファイルが転送中の場合、ネットワークなどの理由で転送が中断されると、次の同じファイルが転送されると、前回中断した場所から転送が継続されます.
4、使用
    //ftp   ip  
    @Value("${sftp.ftp_address}")
    private String ftpAddress;
    //   
    @Value("${sftp.ftp_port}")
    private int ftpPort;
    //   
    @Value("${sftp.ftp_username}")
    private String ftpUsername;
    //  
    @Value("${sftp.ftp_password}")
    private String ftpPassword;

    /**
     *     
     *
     * @param inputStream
     * @param path
     * @param fileName
     * @return
     */
    @Override
    public Map uploadFile(InputStream inputStream, String path, String fileName) {
        Map map = new HashMap();
        Boolean flog = false;
        String msg="";
        SFTPUtil sftpUtil = null;
        try {
            if(path.startsWith("/")){
                sftpUtil = new SFTPUtil();
                sftpUtil.connect(ftpUsername, ftpAddress, ftpPort, ftpPassword);
                sftpUtil.upLoadFile(inputStream, path, fileName);
                flog = true;
                msg = "      ";
            }else {
                log.error("       /  ");
                msg = "       /  ";
            }
        } catch (JSchException e) {
            log.error("  sftp     :", e);
            msg = "       ";
            e.printStackTrace();
        } catch (Exception e) {
            log.error("      :", e);
            msg = "      ";
            e.printStackTrace();
        } finally {
            if (sftpUtil != null) {
                sftpUtil.close();
            }
        }
        map.put("flog", flog);
        map.put("msg", msg);
        return map;
    }

    /**
     *             
     *
     * @param path
     * @return
     */
    @Override
    public Map lsPath(String path) {
        Map map = new HashMap();
        Boolean flog = false;
        String msg="";
        SFTPUtil sftpUtil = null;
        try {
            sftpUtil = new SFTPUtil();
            sftpUtil.connect(ftpUsername, ftpAddress, ftpPort, ftpPassword);
            Vector vector = sftpUtil.ls(path);
            flog = true;
            map.put("flog", flog);
            map.put("list", vector);
            return map;
        } catch (JSchException e) {
            log.error("       :", e);
            msg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            log.error("              :", e);
            msg = "        ";
            e.printStackTrace();
        } finally {
            sftpUtil.close();
        }
        map.put("flog", flog);
        map.put("msg", msg);
        return map;
    }

    /**
     *        
     *
     * @param oldPath
     * @param newPath
     * @return
     */
    @Override
    public Map renameFile(String oldPath, String newPath) {
        Map map = new HashMap();
        Boolean flog = false;
        String msg="";
        SFTPUtil sftpUtil = null;
        try {
            sftpUtil = new SFTPUtil();
            sftpUtil.connect(ftpUsername, ftpAddress, ftpPort, ftpPassword);
            sftpUtil.rename(oldPath, newPath);
            flog = true;
            msg = "         ";
        } catch (JSchException e) {
            log.error("       :", e);
            msg = "       ";
            e.printStackTrace();
        } catch (Exception e) {
            log.error("         :", e);
            msg = "       ";
            e.printStackTrace();
        } finally {
            sftpUtil.close();
        }
        map.put("flog", flog);
        map.put("msg", msg);
        return map;

    }
    /**
     *       
     *
     * @param remotePath
     * @param remoteFileName
     * @return
     */
    @Override
    public void deleteFile(String remotePath, String remoteFileName){
        SFTPUtil sftpUtil = null;
        try {
            sftpUtil = new SFTPUtil();
            sftpUtil.connect(ftpUsername, ftpAddress, ftpPort, ftpPassword);
            sftpUtil.deleteFile(remotePath, remoteFileName);
        } catch (JSchException e) {
            log.error("  sftp     :", e);
            e.printStackTrace();
        }catch (Exception e){
            log.error("      :", e);
            e.printStackTrace();
        }
        finally {
            sftpUtil.close();
        }
    }

参照先:https://blog.csdn.net/zhichao_qzc/article/details/80301994