首页 > 解决方案 > 如何将文本文件 (txt) 写入我的 ftp 服务器?

问题描述

我怎样才能做到这一点?请问谁能帮帮我?我尝试了所有的 Apache 插件,但它不起作用!你知道任何可以帮助我编写txt文件并将它们写入我的FTP服务器的插件吗?我的荣幸。(对不起,我的英语一点也不好听)

标签: java

解决方案


首先,您不能直接在 FTP 上写入文件。您需要在本地编写它,然后将其存储在 FTP 上。试试这个,它对我有用。

public static void main(String[] args) {
    String server = "ftp://ftp.dlptest.com/";
    int port = 21;
    String user = "dlpuser@dlptest.com";
    String pass = "fLDScD4Ynth0p4OJ6bW6qCxjh";

    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        File firstLocalFile = new File("C:/Users/Administrator/Desktop/Book1.xlsx");

        String firstRemoteFile = "Book1.xlsx";
        InputStream inputStream = new FileInputStream(firstLocalFile);

        System.out.println("Start uploading first file");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("The first file is uploaded successfully.");
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
} 

推荐阅读