Java 使用 SFTP 实现文件上传下载(二)

3 篇文章 0 订阅
2 篇文章 0 订阅
package com.lijy.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class FtpUtil {
    /**log*/
    protected static Logger log = Logger.getLogger(FtpUtil.class);

    public static final String NO_FILE = "No such file";

    private ChannelSftp sftp = null;

    private Session sshSession = null;

    private String username;

    private String password;

    private String host;

    private int port;

    public FtpUtil(String username, String password, String host, int port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    /**
     * 连接sftp服务器
     * @return ChannelSftp sftp类型
     * @throws GoPayException
     */
    public ChannelSftp connect() throws GoPayException {
        log.info("FtpUtil-->connect--ftp连接开始>>>>>>host=" + host + ">>>port" + port + ">>>username=" + username);
        JSch jsch = new JSch();
        try {
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            log.info("ftp---Session created.");
            sshSession.setPassword(password);
            Properties properties = new Properties();
            properties.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(properties);
            sshSession.connect();
            log.info("ftp---Session connected.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            log.info("Opening Channel.");
            sftp = (ChannelSftp) channel;
            log.info("ftp---Connected to " + host);
        }
        catch (JSchException e) {
            throw new GoPayException("FtpUtil-->connect异常" + e.getMessage());
        }
        return sftp;
    }

    /**
     * 载单个文件
     * @param directory       :远程下载目录(以路径符号结束)
     * @param remoteFileName  FTP服务器文件名称 如:xxx.txt ||xxx.txt.zip
     * @param localFile       本地文件路径 如 D:\\xxx.txt
     * @return
     * @throws GoPayException
     */
    public File downloadFile(String directory, String remoteFileName,String localFile) throws GoPayException {
        log.info(">>>>>>>>FtpUtil-->downloadFile--ftp下载文件"+remoteFileName+"开始>>>>>>>>>>>>>");
        connect();
        File file = null;
        OutputStream output = null;
        try {
            file = new File(localFile);
            if (file.exists()){
                file.delete();
            }
            file.createNewFile();
            sftp.cd(directory);
            output = new FileOutputStream(file);
            sftp.get(remoteFileName, output);
            log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
        }
        catch (SftpException e) {
            if (e.toString().equals(NO_FILE)) {
                log.info(">>>>>>>>FtpUtil-->downloadFile--ftp下载文件失败" + directory +remoteFileName+ "不存在>>>>>>>>>>>>>");
                throw new GoPayException("FtpUtil-->downloadFile--ftp下载文件失败" + directory +remoteFileName + "不存在");
            }
            throw new GoPayException("ftp目录或者文件异常,检查ftp目录和文件" + e.toString());
        }
        catch (FileNotFoundException e) {
            throw new GoPayException("本地目录异常,请检查" + file.getPath() + e.getMessage());
        }
        catch (IOException e) {
            throw new GoPayException("创建本地文件失败" + file.getPath() + e.getMessage());
        }
        finally {
            if (output != null) {
                try {
                    output.close();
                }
                catch (IOException e) {
                    throw new GoPayException("Close stream error."+ e.getMessage());
                }
            }
            disconnect();
        }

        log.info(">>>>>>>>FtpUtil-->downloadFile--ftp下载文件结束>>>>>>>>>>>>>");
        return file;
    }

    /**
     * 上传单个文件
     * @param directory      :远程下载目录(以路径符号结束)
     * @param uploadFilePath 要上传的文件 如:D:\\test\\xxx.txt
     * @param fileName       FTP服务器文件名称 如:xxx.txt ||xxx.txt.zip
     * @throws GoPayException
     */
    public void uploadFile(String directory, String uploadFilePath, String fileName)
            throws GoPayException {
        log.info(">>>>>>>>FtpUtil-->uploadFile--ftp上传文件开始>>>>>>>>>>>>>");
        FileInputStream in = null;
        connect();
        try {
            sftp.cd(directory);
        }
        catch (SftpException e) {
            try {
                sftp.mkdir(directory);
                sftp.cd(directory);
            }
            catch (SftpException e1) {
                throw new GoPayException("ftp创建文件路径失败,路径为" + directory);
            }

        }
        File file = new File(uploadFilePath);
        try {
            in = new FileInputStream(file);
            sftp.put(in, fileName);
        }
        catch (FileNotFoundException e) {
            throw new GoPayException("文件不存在-->" + uploadFilePath);
        }
        catch (SftpException e) {
            throw new GoPayException("sftp异常-->" + e.getMessage());
        }
        finally {
            if (in != null){
                try {
                    in.close();
                }
                catch (IOException e) {
                    throw new GoPayException("Close stream error."+ e.getMessage());
                }
            }
            disconnect();
        }
        log.info(">>>>>>>>FtpUtil-->uploadFile--ftp上传文件结束>>>>>>>>>>>>>");
    }

    private synchronized static File certTempEmptyile() {
        String dirPath = SystemConfig.getProperty("down_settle_file.temp_path");
        FileUtil.mkDir(dirPath);
        String newFileName = System.currentTimeMillis() + ".txt";
        String filePath = dirPath + File.separator + newFileName;
        File file = new File(filePath);
        return file;
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
                this.sftp = null;
                log.info("sftp is closed already");
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
                this.sshSession = null;
                log.info("sshSession is closed already");
            }
        }
    }




}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是使用JSch实现Java SFTP批量上传文件的完整代码: ``` import com.jcraft.jsch.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Properties; public class SftpBatchUpload { private static final String HOST = "sftp.example.com"; // SFTP服务器地址 private static final int PORT = 22; // SFTP服务器端口号 private static final String USERNAME = "username"; // SFTP服务器登录用户名 private static final String PASSWORD = "password"; // SFTP服务器登录密码 private static final String REMOTE_PATH = "/upload/"; // SFTP服务器上传文件路径 public static void main(String[] args) { JSch jsch = new JSch(); Session session = null; ChannelSftp channelSftp = null; try { // 创建SFTP会话 session = jsch.getSession(USERNAME, HOST, PORT); session.setPassword(PASSWORD); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); // 批量上传文件 String localPath = "C:\\local\\path\\"; // 本地文件路径 File localDir = new File(localPath); File[] localFiles = localDir.listFiles(); for (File localFile : localFiles) { if (localFile.isFile()) { String remoteFile = localFile.getName(); channelSftp.put(new FileInputStream(localFile), REMOTE_PATH + remoteFile); System.out.println("上传文件" + localFile.getAbsolutePath() + "到" + REMOTE_PATH + remoteFile + "成功!"); } } } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { // 关闭SFTP连接和会话 if (channelSftp != null) { channelSftp.disconnect(); } if (session != null) { session.disconnect(); } } } } ``` 其中,需要替换的常量有: - HOSTSFTP服务器地址 - PORT:SFTP服务器端口号 - USERNAME:SFTP服务器登录用户名 - PASSWORD:SFTP服务器登录密码 - REMOTE_PATH:SFTP服务器上传文件路径 代码中的批量上传文件逻辑是,将本地路径为C:\local\path\下的所有文件上传SFTP服务器的REMOTE_PATH路径下。如果需要更改本地文件路径或者上传文件的后缀名等属性,可以根据实际需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值