如何将文本文件(txt)写入ftp服务器?

时间:2019-10-06 06:02:51

标签: java

我该怎么做?谁能帮助我? 我尝试了所有Apache插件,但没有用! 您是否知道可以帮助我编写txt文件并将其写入FTP服务器的插件? 我的荣幸。 (对不起,我的英语根本不懂)

1 个答案:

答案 0 :(得分:0)

首先,您不能直接在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();
        }
    }
}