21和22端口 在java中的使用

本文介绍了一款SFTP工具的实现细节,包括如何通过Java进行SFTP服务器的连接、文件的上传与下载等功能,并提供了具体的代码示例。

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

在FileZilla 中:
- 用sftp协议连接Server ,需要用port 22
- 用ftp协议连接Server, 用port21

一个控制端口一个数据传输端口。
端口20才是真正传输所用到的端口,端口21只用于FTP的登陆认证。

sftp工具

package com.demo.utils;

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.*;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * sftp 工具类
 *
 * @version v1.0
 * @date 2019/8/13 11:34
 */
@Component
@Slf4j
public class SftpUtils {

    private ChannelSftp sftp;
    private boolean isReady = false;
    private FtpConfig config;
    private Session sshSession;

    @Data
    private class FtpConfig {
        private String server;
        private String port;
        private String username;
        private String password;
        private String encoding;
    }

    /**
     * 连接sftp服务器
     */
    public SftpUtils(String server, String port, String username, String password, String encoding) {
        config = new FtpConfig();
        config.setServer(server);
        config.setPort(port);
        config.setUsername(username);
        config.setPassword(password);
        config.setEncoding(encoding);
        log.info("server = {}, port = {}, username = {}, password = {}", server, port, username, password);
    }

    public SftpUtils() {
    }

    private void setReady() throws Exception {
        try {
            if (!isReady) {
                JSch jsch = new JSch();
                sshSession = jsch.getSession(config.getUsername(), config.getServer(), Integer.parseInt(config.getPort()));
                log.info("Session created.");
                sshSession.setPassword(config.getPassword());
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);
                isReady = true;
                log.info("Session is ready.");
            }
            if (sshSession != null && !sshSession.isConnected()) {
                sshSession.connect();
                Channel channel = sshSession.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
                Class<ChannelSftp> c = ChannelSftp.class;
                Field f = c.getDeclaredField("server_version");
                f.setAccessible(true);
                f.set(sftp, 2);
                sftp.setFilenameEncoding(config.getEncoding());
                log.info("Session is connected.");
            }
        } catch (Exception e) {
            this.close();
            log.error("sftp连接服务器出错,host:" + config.getServer(), e);
            throw e;
        }
    }

    /**
     * 下载文件
     *
     * @param directory    文件所在目录
     * @param downloadFile 下载的文件url
     * @param saveFile     存在本地的路径
     * @throws Exception
     */
    public boolean downloadFile(String directory, String downloadFile, String saveFile) throws Exception {
        log.info("directory:{},downloadFile:{},saveFile:{}", directory, downloadFile, saveFile);
        try {
            setReady();
            sftp.cd(directory);
            File localFile = new File(saveFile);
            if (!localFile.exists()) {
                if (localFile.getParentFile() != null && !localFile.getParentFile().exists()) {
                    localFile.getParentFile().mkdirs();
                }
                localFile.createNewFile();
            }
            sftp.get(downloadFile, new FileOutputStream(localFile));
            return true;
        } catch (Exception e) {
            log.error("sftp下载文件出错,directory:" + directory, e);
            throw e;
        }
    }


    /**
     * 上传文件
     * @param filePath
     * @param fileName
     * @param file
     * @return
     * @throws Exception
     */
    public boolean uploadFile(String filePath, String fileName, File file) throws Exception {
        log.info("directory:{},downloadFile:{},saveFile:{}", filePath, fileName, file);
        try {
            setReady();
            sftp.cd(filePath);
            sftp.put(new FileInputStream(file), fileName);
            return true;
        } catch (Exception e) {
            log.error("sftp上传文件出错,fileName:" + fileName, e);
            throw e;
        }
    }

    // 获取文件行数
    public long getLineCountRemoveEmpty(String directory,String fileName) throws Exception {
        String tmp;
        try
        {
            long lines = 0;
            BufferedReader reader = getBufferedReader(directory, fileName);
            while ((tmp=reader.readLine())!=null){
                if(tmp.equals(""));
                else {
                    lines++;
                }
            }
            return lines;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            log.error("sftp获取文件行数,directory:{},fileName:{},errorInfo",directory,fileName, e);
            throw e;
        }

        return 0;
    }

    // 获取文件行数
    public BufferedReader getBufferedReader(String directory,String fileName) throws Exception{
        setReady();
        sftp.cd(directory);
        InputStream inputStream = sftp.get(fileName);
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);
        return br;
    }

    /**
     * 列出目录下的文件
     *
     * @param directory 文件所在目录
     * @throws Exception
     */
    public List<String> listFiles(String directory) throws Exception {
        log.info("directory:{}", directory);
        setReady();
        Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
        if (vector.isEmpty()) {
            return Collections.emptyList();
        }
        return vector.stream().map(ChannelSftp.LsEntry::getFilename).collect(Collectors.toList());
    }

    public void close() throws IOException {
        if (sftp != null && sftp.isConnected()) {
            sftp.disconnect();
        }
        if (sshSession != null && sshSession.isConnected()) {
            sshSession.disconnect();
        }
        isReady = false;
        log.info("JSCH session close");
    }

    public static void main(String[] args) throws Exception {
        SftpUtils sftpUtils = new SftpUtils("47.112.219.114", "32122", "root", "qiaoyuan@2019", "UTF-8");
        List<String> files = sftpUtils.listFiles("/usr/local/test");
        for (String file:files){
            System.out.println(file);
        }
        System.out.println(sftpUtils.getBufferedReader("/usr/local/test", "test").readLine());
        sftpUtils.close();
    }
}

ftp工具

hutool-all-5.0.7.jar包中的

cn.hutool.extra.ftp.Ftp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值