JAVA读取FTP服务器文件内容

1 篇文章 0 订阅
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

public class FTPUtil {

    /**
     * 打开FTP服务链接
     * @param ftpHost
     * @param ftpPort
     * @param ftpUserName
     * @param ftpPassword
     */
    public static FTPClient getFTPClient(String ftpHost, Integer ftpPort, String ftpUserName, String ftpPassword){
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.setConnectTimeout(60000);
            if(ftpPort != null){
                ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            }else {
                ftpClient.connect(ftpHost);// 连接FTP服务器
            }
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                if (ftpClient.login(ftpUserName, ftpPassword)) {// 登陆FTP服务器
                    if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                            "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                        ftpClient.setControlEncoding("UTF-8");
                    }else {
                        ftpClient.setControlEncoding("GBK");
                    }
                    ftpClient.enterLocalPassiveMode();// 设置被动模式
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置传输的模式,以二进制流的方式读取
                    ftpClient.enterLocalPassiveMode();
                    System.out.println("FTP服务连接成功!");
                }else {
                    System.out.println("FTP服务用户名或密码错误!");
                    disConnection(ftpClient);
                }
            }else {
                System.out.println("连接到FTP服务失败!");
                disConnection(ftpClient);
            }
        } catch (SocketException e) {
            e.printStackTrace();
            disConnection(ftpClient);
            System.out.println("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            disConnection(ftpClient);
            System.out.println("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    /**
     * 关闭FTP服务链接
     * @throws IOException
     */
    public static void disConnection(FTPClient ftpClient){
        try {
            if(ftpClient.isConnected()){
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件夹下的所有文件信息
     * @param path 文件路径
     */
    public static FTPFile[] getFTPDirectoryFiles(FTPClient ftpClient,String path){
        FTPFile[] files = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            files = ftpClient.listFiles();
        }catch (Exception e){
            e.printStackTrace();
            //关闭连接
            disConnection(ftpClient);
            System.out.println("FTP读取数据异常!");
        }
        return files;
    }


    /**
     * 获取文件夹下的所有文件信息
     * @param path 文件路径
     */
    public static InputStream getFTPFile(FTPClient ftpClient,String path,String fileName){
        InputStream in = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            FTPFile[] files = ftpClient.listFiles();
            if(files.length > 0){
                in  = ftpClient.retrieveFileStream(fileName);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("FTP读取数据异常!");
        }finally {
            //关闭连接
            disConnection(ftpClient);
        }
        return in;
    }

    public static void main(String args[]){
        InputStream in = null;
        BufferedReader br = null;
        try{
            String path = "/home/ftp/";
            //读取单个文件
            FTPClient ftpClient = getFTPClient("10.1.1.1",21,"username","123456");
            String fileName = "person.txt";
            in = getFTPFile(ftpClient,path,fileName);
            if(in != null){
                br = new BufferedReader(new InputStreamReader(in,"GBK"));
                String data = null;
                while ((data = br.readLine()) != null) {
                    String[] empData = data.split(";");
                    System.out.println(empData[0]+" "+empData[1]);
                }
            }

            //读取文件夹下的所有文件
            FTPClient ftpClient1 = getFTPClient("10.1.1.1",21,"username","123456");
            FTPFile[] files = getFTPDirectoryFiles(ftpClient1,path);
            if(files != null && files.length > 0){
                for (int i = 0; i < files.length; i++) {
                    if(files[i].isFile()){
                        in = ftpClient1.retrieveFileStream(files[i].getName());
                        br = new BufferedReader(new InputStreamReader(in,"GBK"));
                        System.out.println(files[i].getName());
                    }
                }
            }
            //关闭连接
            disConnection(ftpClient1);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                //关闭流
                if (br != null)
                    br.close();
                if (in != null)
                    in.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

 

  • 10
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
使用Java解压FTP服务器上的文件需要以下步骤: 第一步,建立与FTP服务器的连接。可以使用Java中的org.apache.commons.net.ftp.FTPClient类来实现连接。首先创建一个FTPClient对象,然后使用connect()方法连接到FTP服务器,并使用login()方法进行登录验证。 第二步,切换到FTP服务器上的目标压缩文件所在的目录。可以使用changeWorkingDirectory()方法指定目录路径。 第三步,从FTP服务器上下载压缩文件到本地。使用retrieveFile()方法将压缩文件下载到本地。 第四步,关闭与FTP服务器的连接。 第五步,使用Java的压缩解压缩工具类,例如java.util.zip.ZipInputStream或java.util.zip.GZIPInputStream,来解压下载到本地的压缩文件。可以使用FileInputStream读取压缩文件的输入流,并将其传递给解压缩工具类的构造函数。 第六步,遍历解压缩后的文件,并进行相关操作。 以下是一个示例代码,展示如何使用Java解压FTP服务器上的文件: ```java import org.apache.commons.net.ftp.FTPClient; import java.io.*; public class FTPFileDecompression { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String password = "password"; String remoteFilePath = "/path/to/zipfile.zip"; String localFilePath = "path/to/save/file.zip"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(remoteFilePath); File localFile = new File(localFilePath); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); ftpClient.retrieveFile(remoteFilePath, outputStream); outputStream.close(); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } // 解压缩文件 try { FileInputStream fileInputStream = new FileInputStream(localFile); ZipInputStream zipInputStream = new ZipInputStream(fileInputStream); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { String entryName = zipEntry.getName(); File file = new File(entryName); // 对解压缩后的文件进行操作 // ... } zipInputStream.close(); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码提供了一个基本框架,你需要根据实际的FTP服务器文件路径进行修改和调整。同时,你可能还需要处理登录失败、目录不存在、文件不存在等异常情况。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值