栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA 读取ftp和sftp文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA 读取ftp和sftp文件

1、读取ftp文件 1.1、maven依赖配置
        
            commons-net
            commons-net
            3.6
        
1.2、代码(读取文件列表||文件内容)
package cn.com.beijiaoguzai.test;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;


public class FtpUtil {

    
    public static FTPClient getFtpClient(String url,int port,String username,String password) throws Exception {
        FTPClient ftp = null;
        int reply;
        ftp = new FTPClient();
        // 设置timeout时间
        ftp.setConnectTimeout(30000);
        ftp.connect(url,port);
        ftp.login(username,password);
        //ftp.setFileType(FTP.ASCII_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return null;
        }

        //设置编码格式
        if(FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8","ON"))){
            ftp.setControlEncoding("UTF-8");
        }else{
            ftp.setControlEncoding("GBK");
        }

        return ftp;
    }

    
    public static InputStream getFTPFileInputStream(FTPClient ftpClient,String path,String fileName){
        InputStream in = null;
        try {
            if(ftpClient == null){
                return in;
            }
            ftpClient.changeWorkingDirectory(path);
            FTPFile[] files = ftpClient.listFiles();


            if(files.length > 0){
                //解决中文路径问题
                in = ftpClient.retrieveFileStream(new String(fileName.getBytes("gbk"), FTP.DEFAULT_CONTROL_ENCODING));

            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("FTP 读取数据异常!");
        }finally{
            //关闭连接
            if(ftpClient != null){
                disConnection(ftpClient);
            }
            return in;
        }
    }

    
    public static String getFtpFile(String url,int port,String username,String password,String path,String fileName,String encoding) throws Exception{
        FTPClient ftpClient = getFtpClient(url,port,username,password);
        if(ftpClient == null){
            System.out.println("连接失败!");
            return null;
        }
        BufferedReader br = null;
        InputStream in = null;
        in = getFTPFileInputStream(ftpClient,path,fileName);
        StringBuffer result = new StringBuffer();
        if(in == null){
            System.out.println("读取文件失败!");
            return null;
        }
        try {
            if(StringUtils.isEmpty(encoding)){
                encoding = "UTF-8";
            }
            br = new BufferedReader(new InputStreamReader(in, encoding));
            String data = null;
            while ((data = br.readLine()) != null) {
                result.append(data+"n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭ftp连接
            disConnection(ftpClient);
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    //关闭io流
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result.toString();
    }

    
    public static FTPFile[] getFTPDirectoryFiles(FTPClient ftpClient,String path) {
        FTPFile[] files = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            files = ftpClient.listFiles();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("FTP读取数据异常!");
        }
        //关闭连接
        //disConnection(ftpClient);
        return files;
    }
    
    public static void disConnection(FTPClient ftpClient) {
        try{
            if(ftpClient.isConnected()){
                ftpClient.disconnect();
            }
        }catch(IOException e) {
            e.printStackTrace();
        }

    }

    
    public static boolean getFileStatus(String fileName){
        boolean resutl = false;
        if(StringUtils.isNotEmpty(fileName)){
            int index = fileName.lastIndexOf(".");
            if(index > 0){
                String fileFormat = fileName.substring(index);

                if(".txt".equalsIgnoreCase(fileFormat) || ".csv".equalsIgnoreCase(fileFormat)){
                    resutl = true;
                }
            }
        }
        return resutl;
    }

    public static void main(String[] args) {
        String url = "192.168.1.139";
        int port = 21;
        String username = "ftpuser";
        String password = "ftpuser";

        FTPClient ftpClient = null;
        try {
            ftpClient = getFtpClient(url,port,username,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = "/";
        //获取目录下文件列表
        System.out.println("获取到的文件是:");
        FTPFile[] ftpFiles = getFTPDirectoryFiles(ftpClient,path);
        for(FTPFile f : ftpFiles){
            if(getFileStatus(f.getName())){
                System.out.println(f.getName());
            }
        }
        System.out.println();
        System.out.println("文件内容是:");
        String fileName = "人员名单.txt";
        String encoding = "UTF-8";

        //获取某个ftp文件内容
        String fileData = null;
        try {
            fileData = getFtpFile(url,port,username,password,path,fileName,encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(fileData);
    }
}
1.3、执行结果
获取到的文件是:
1.txt
2.txt
abc.txt
sys_data_two2_20220516.csv
人员名单.txt

文件内容是:
编号,姓名,年龄,性别,籍贯,职业,爱好
1001,张飞,25,男,河北,辅助,打架
1002,李白,36,男,北京,诗人,打野
1003,王昭君,18,陕西,法师,出塞


进程已结束,退出代码0

中途遇到一个比较坑的问题,就是ftpClient.retrieveFileStream(fileName) 方法,读取中文文件时候,获取的一直是null,从网上查了大半天,都是修改编码格式,但是一直没有效果,因为我是用VMware开的window10虚拟机上面开启的ftp服务,最后发现了解决办法一并奉上,具体步骤如下:
第一步,打开控制面板

第二步,点击管理工具

第三步,双击 Internet Information Services (IIS)管理器

第四步,点开左侧网站,点击 Ftp Server(你自己的ftp名字,有可能不一样)

第五步,选中FTP 防火墙支持,点击右侧高级设置,然后将允许 UTF-8 改为False即可

2、读取SFTP文件  2.1、maven依赖配置
        
            com.jcraft
            jsch
            0.1.54
        
2.2、代码(读取文件列表||文件内容)
package cn.com.beijiaoguzai.test;

import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Vector;


public class SftpUtil {

    private static ChannelSftp sftp = null;
    private static Session session = null;

    
    public static ChannelSftp sftpConnect(String username,String password,String host,int port,String privateKey) throws Exception {

        JSch jsch = new JSch();
        if (privateKey != null && !"".equals(privateKey)) {
             jsch.addIdentity(privateKey);// 设置私钥
         }
        //用户名,主机,端口号
        session = jsch.getSession(username, host, port);
        //密码
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        // 设置timeout时间
        session.setTimeout(30000);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        return sftp;
    }

     
     public static Vector listFiles(String directory) throws SftpException {

         return sftp.ls(directory);
     }
    
    public static boolean getFileStatus(String fileName){
        boolean resutl = false;
        if(StringUtils.isNotEmpty(fileName)){
            int index = fileName.lastIndexOf(".");
            if(index > 0){
                String fileFormat = fileName.substring(index);

                if(".txt".equalsIgnoreCase(fileFormat) || ".csv".equalsIgnoreCase(fileFormat)){
                    resutl = true;
                }
            }
        }
        return resutl;
    }
    
    public static String getFtpData( String fileName,String ftpPath) throws SftpException, IOException {
        try {
            if (null == sftp) {
                return null;
            }
            sftp.cd(ftpPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        InputStream in = sftp.get(fileName);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line+"n");
        }
        return sb.toString();
    }

    
    public static void closeChannel() {
        if (sftp != null) {
            sftp.disconnect();
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        String host = "192.168.1.139";
        int port = 23;
        String username = "sftpuser";
        String password = "sftpuser";
        String ftpPath = "/";
        try {
            //创建连接
            sftpConnect(username,password,host,port,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //获取文件列表
            Vector vector =listFiles(ftpPath);
            Iterator iterator = vector.iterator();
            System.out.println("文件列表:");
            while (iterator.hasNext()) {
                ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
                //文件名称
                if(getFileStatus(file.getFilename())){
                    System.out.println(file.getFilename());
                }
            }
            System.out.println();
            String fileName = "人员名单.txt";
            //提取文件内容
            String data = getFtpData(fileName,ftpPath);
            System.out.println("如下文件内容:");
            System.out.println(data);
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            SftpUtil.closeChannel();
        }

    }
}

2.3、执行结果
Picked up _JAVA_OPTIONS: -Xmx5G
文件列表:
sftp1.txt
人员名单.txt
新建文本文档.txt

如下文件内容:
编号,姓名,年龄,性别,籍贯,职业,爱好
1001,张飞,25,男,河北,辅助,打架
1002,李白,36,男,北京,诗人,打野
1003,王昭君,18,陕西,法师,出塞

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/917977.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号