java ftp链接服务器,读取服务器csv文件

1.下载 apache commons-net-1.4.1 jar包

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>1.4.1</version>
</dependency>
<dependency>
    <groupId>net.sourceforge.javacsv</groupId>
    <artifactId>javacsv</artifactId>
    <version>2.0</version>
</dependency>

2.创建 FtpClientUtil 工具类

package com.example.diagnosis.util;

import com.csvreader.CsvReader;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * ftp连接管理(使用apache commons-net-1.4.1 lib)
 */
public class FtpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpClientUtil.class);
    private FTPClient ftpClient = null;
    private String server;
    private int port;
    private String userName;
    private String userPassword;

    public FtpClientUtil(String server, int port, String userName, String userPassword) {
        this.server = server;
        this.port = port;
        this.userName = userName;
        this.userPassword = userPassword;
    }

    /**
     * 链接到服务器
     *
     * @return
     * @throws Exception
     */
    public boolean open() {
        if (ftpClient != null && ftpClient.isConnected()) {
            return true;
        }
        try {
            ftpClient = new FTPClient();
            // 连接
            ftpClient.connect(this.server, this.port);
            ftpClient.login(this.userName, this.userPassword);
            ftpClient.enterLocalPassiveMode();
            // 检测连接是否成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.close();
                System.exit(1);
            }
            return true;
        } catch (Exception ex) {
            // 关闭
            this.close();
            logger.error("FTP连接失败...");
            return false;
        }

    }

    private boolean cd(String dir) throws IOException {
        if (ftpClient.changeWorkingDirectory(dir)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取目录下所有的文件名称
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public List<String> getFileList(String filePath, String ext, List<String> arrList) throws IOException {
        if (filePath.startsWith("/") && filePath.endsWith("/")) {
            if (ftpClient.changeWorkingDirectory(filePath)) {
                FTPFile[] list = ftpClient.listFiles();
                for (FTPFile ftpFile : list) {
                    if (ftpFile.isFile()) {
                        if (ftpFile.getName().endsWith(ext)) {
                            arrList.add(filePath + ftpFile.getName());
                        }
                    } else if (ftpFile.isDirectory()) {
                        if (!".".equals(ftpFile.getName()) && !"..".equals(ftpFile.getName())) {
                            getFileList(filePath + ftpFile.getName() + "/", ext, arrList);
                        }
                    }
                }
            }
//        ftpClient.setControlEncoding("GBK");
        }
        return arrList;
    }

    public List<String> fileList(String filePath) throws IOException {
        List<String> arrList = new CopyOnWriteArrayList<>();
        if (filePath.startsWith("/") && filePath.endsWith("/")) {
            if (ftpClient.changeWorkingDirectory(filePath)) {
                ftpClient.changeWorkingDirectory(filePath);
                FTPFile[] list = ftpClient.listFiles();
                for (FTPFile ftpFile : list) {
                    arrList.add(ftpFile.getName());
                }
            }
        }
        return arrList;
    }

    /**
     * <b>将一个IO流解析,转化数组形式的集合<b>
     *
     * @param in 文件inputStream流
     */
    public List<String[]> csv(InputStream in) {
        List<String[]> csvList = new ArrayList<String[]>();
        if (null != in) {
            CsvReader reader = new CsvReader(in, ',', Charset.forName("GBK"));
            try {
                // 遍历每一行,若有#注释部分,则不处理,若没有,则加入csvList
                while (reader.readRecord()) {
                    if (!reader.getValues()[0].contains("#"))// 清除注释部分
                    {
                        csvList.add(reader.getValues());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            reader.close();
        }
        return csvList;
    }

    /**
     * 获取csv文件内容.
     */
    public List<String[]> getFtpFileContent(String fileName, String filePath, List<String[]> fileContent) throws IOException {
        ftpClient.changeWorkingDirectory(filePath);
        InputStream in = ftpClient.retrieveFileStream(fileName);
        fileContent.addAll(csv(in));
        in.close();
        ftpClient.completePendingCommand();
        return fileContent;
    }

    /**
     * 关闭链接
     */
    public void close() {
        try {
            if (ftpClient != null && ftpClient.isConnected())
                ftpClient.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {

        this.ftpClient = ftpClient;
    }
}

3.创建测试类Test

package com.example.diagnosis;

import com.example.diagnosis.util.FtpClientUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class test {
    public static void main(String[] args) {
        FtpClientUtil ftpClientUtil = new FtpClientUtil(
                "host", 80,
                "admin", "admin");
        if (ftpClientUtil.open()) {
            //ftp链接成功
            //csv文件路径
            String pathFile = "";
            try {
                List<String> fileList = ftpClientUtil.getFileList(pathFile + "/", "csv", new ArrayList<>());
                for (String s : fileList) {
                    //截取文件名
                    String fileName = s.substring(s.lastIndexOf("/") + 1);
                    //截取文件路径
                    String filePath = s.substring(0, s.lastIndexOf("/") + 1);
                    List<String[]> ftpFileContent = ftpClientUtil.getFtpFileContent(fileName, filePath, new ArrayList<>());
                    System.out.println(ftpFileContent);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java提供了一些类和API来实现FTP文件服务器。以下是一个简单的FTP文件服务器的示例代码: ```java import java.io.*; import java.net.*; import org.apache.commons.net.ftp.*; public class FTPServer { public static void main(String[] args) { FTPServer server = new FTPServer(); server.start(); } public void start() { int port = 21; try { ServerSocket serverSocket = new ServerSocket(port); System.out.println("FTP Server started on port " + port); while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("Accepted connection from " + clientSocket.getInetAddress().getHostAddress()); FTPConnection connection = new FTPConnection(clientSocket); connection.start(); } } catch (IOException ex) { System.err.println("Error starting FTP server: " + ex.getMessage()); } } } class FTPConnection extends Thread { private Socket clientSocket; private FTPServer server; private FTPClient ftp; public FTPConnection(Socket clientSocket) { this.clientSocket = clientSocket; this.server = server; ftp = new FTPClient(); } public void run() { try { ftp.connect(clientSocket.getInetAddress().getHostName()); ftp.login("anonymous", ""); ftp.enterLocalPassiveMode(); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream())); String line = null; out.print("220 FTP Server ready.\r\n"); out.flush(); while ((line = in.readLine()) != null) { if (line.startsWith("USER")) { out.print("331 Password required for " + line.substring(5) + "\r\n"); out.flush(); } else if (line.startsWith("PASS")) { out.print("230 User logged in.\r\n"); out.flush(); } else if (line.startsWith("QUIT")) { out.print("221 Goodbye.\r\n"); out.flush(); break; } else if (line.startsWith("TYPE")) { out.print("200 Command okay.\r\n"); out.flush(); } else if (line.startsWith("LIST")) { FTPFile[] files = ftp.listFiles(); out.print("150 Opening ASCII mode data connection for file list.\r\n"); out.flush(); for (FTPFile file : files) { out.print(file.getName() + "\r\n"); out.flush(); } out.print("226 Transfer complete.\r\n"); out.flush(); } else if (line.startsWith("RETR")) { out.print("150 Opening BINARY mode data connection for " + line.substring(5) + "\r\n"); out.flush(); String fileName = line.substring(5); OutputStream os = clientSocket.getOutputStream(); ftp.retrieveFile(fileName, os); out.print("226 Transfer complete.\r\n"); out.flush(); } else { out.print("502 Command not implemented.\r\n"); out.flush(); } } ftp.disconnect(); clientSocket.close(); } catch (IOException ex) { System.err.println("Error handling FTP connection: " + ex.getMessage()); } } } ``` 这个例子使用Apache Commons Net库来实现FTP连接和文件传输。它可以处理一些基本的FTP命令,如USER、PASS、LIST和RETR。你可以根据需要添加更多的功能和命令来实现一个更完整的FTP文件服务器

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值