2011-02-26 28 views
0

在我的Java swing程序中,我使用Scanner和BufferedWriter讀取,編輯和保存本地文件夾中的各種文本文件。有沒有一種簡單的方法可以保留我當前的代碼,但是,使用FTP編輯Web文件而不是本地文件?感謝大家。Java和FTP來編輯在線文本文件

回答

1

您可以使用URL和URLConnection類來獲取位於FTP服務器上的文件的InputStreams和OutputStreams。

要讀取文件

URL url = new URL("ftp://user:[email protected]/myfile.txt"); 
InputStream in = url.openStream(); 

寫一個文件

URL url = new URL("ftp://user:[email protected]/myfile.txt"); 
URLConnection conn = url.openConnection(); 
conn.setDoOutput(true); 
OutputStream out = conn.getOutputStream(); 
+0

'URL url = new URL(「ftp:// user:[email protected]/myfile.txt」); URLConnection connection = url.openConnection(); connection.setDoOutput(真); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); (「早上好Starshine!地球說HELLOOO !!」); (); out.close – kAmol 2014-05-31 20:12:23

1

我試圖達到相同,這些問題的答案對我幫助很大:

Adding characters to beginning and end of InputStream in Java(中一個標記爲右側顯示如何將自定義字符串添加到InputStream)

Uploading a file to a FTP server from android phone?(從維韋克·庫馬爾·米特拉的一個演示如何上傳文件)

我增添了新的文字,我在網上的文件這樣的結尾:

FTPClient con = null; 

     try { 
      con = new FTPClient(); 
      con.connect(Hostname); 

      if (con.login(FTPUsername, FTPPassword)) { 
       con.enterLocalPassiveMode(); // important! 
       con.setFileType(FTP.BINARY_FILE_TYPE); 

       InputStream onlineDataIS = urlOfOnlineFile.openStream(); 

       String end = "\nteeeeeeeeeeeeeeeeest"; 
       List<InputStream> streams = Arrays.asList(
         onlineDataIS, 
         new ByteArrayInputStream(end.getBytes())); 
       InputStream resultIS = new SequenceInputStream(Collections.enumeration(streams)); 

       // Stores a file on the server using the given name and taking input from the given InputStream. 
       boolean result = con.storeFile(PathOfTargetFile, resultIS); 
       onlineDataIS.close(); 
       resultIS.close(); 
       if (result) Log.v("upload result", "succeeded"); 
       con.logout(); 
       con.disconnect(); 
      } 
      return "Writing successful"; 
     } catch (IOException e) { 
      // some smart error handling 
     } 

希望有所幫助。