2014-09-27 287 views
2

我需要Java網絡編程方面的幫助。我試圖創建一個新的文本文件到FTP服務器。我在網上找到這個代碼示例,但它只創建一個目錄。 如何將其更改爲文本文件格式?在FTP服務器上創建一個文本文件(Commons-net)

下面的代碼:

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(); 
    } 
} 

對不起,我的英語不好。

回答

1

我不是這個庫的專家,但我認爲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); 
    } 

[編輯]注意,由於該方法獲取InputStream作爲參數,你最終可以用別的東西比本地文件作爲輸入:你也可以直接從字符串讀取。

相關問題