在FTP服务器(Commons-net)中创建一个文本文件



我需要Java网络编程方面的帮助。我试图创建一个新的文本文件到FTP服务器。我在互联网上找到了这个代码示例,但它只创建了一个目录。如何将其更改为文本文件格式?

这是代码:

public class FTPCreateDirDemo {
private static void showServerReply(FTPClient ftpClient) {
    String[] replies = ftpClient.getReplyStrings();
    if (replies != null && replies.length > 0) {
        for (String aReply : replies) {
            System.out.println("SERVER: " + aReply);
        }
    }
}
public static void main(String[] args) {
    String server = "www.yourserver.com";
    int port = 21;
    String user = "username";
    String pass = "password";
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(server, port);
        showServerReply(ftpClient);
        int replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            System.out.println("Operation failed. Server reply code: " + replyCode);
            return;
        }
        boolean success = ftpClient.login(user, pass);
        showServerReply(ftpClient);
        if (!success) {
            System.out.println("Could not login to the server");
            return;
        }
        // Creates a directory
        String dirToCreate = "/upload123";
        success = ftpClient.makeDirectory(dirToCreate);
        showServerReply(ftpClient);
        if (success) {
            System.out.println("Successfully created directory: " + dirToCreate);
        } else {
            System.out.println("Failed to create directory. See server's reply.");
        }
        // logs out
        ftpClient.logout();
        ftpClient.disconnect();
    } catch (IOException ex) {
        System.out.println("Oops! Something wrong happened");
        ex.printStackTrace();
    }
}

抱歉我英语不好。

我不是这个库的专家,但我认为FTP更多的是从远程服务器发送/接收文件,而不是直接访问远程文件系统。因此,要创建远程文件,应该首先在本地创建(例如,在临时目录中),然后将其发送到远程服务器。检查文档:https://commons.apache.org/proper/commons-net/javadocs/api-1.4.1/org/apache/commons/net/ftp/FTPClient.html

尤其是这种方法:

public boolean storeFile(String remote, InputStream local)
              throws IOException

给定一个本地文件"foo.txt",您可以创建一个InputStream并使用该输入流将文件发送到远程端:

    try (FileInputStream inputStream = new FileInputStream("foo.txt");) {
        ftpClient.storeFile("foo.txt", inputStream);
    }

[edit]请注意,由于方法采用InputStream作为参数,因此您最终可以使用本地文件以外的其他文件作为输入:您也可以直接从String中读取。

我知道这是一个旧线程,但对于那些正在寻找通过FTP将Java字符串直接写入远程文本文件的人来说,以下是我使用字符串的常规InputStream找到的解决方案:

String inputString = "Filecontent for remote Server";
try (InputStream targetStream = new ByteArrayInputStream(inputString.getBytes())) {
     ftpClient.storeFile("foo.txt", targetStream);
}

相关内容

最新更新