2011-01-20 107 views
0
try 
     { 
      URL url = new URL("http://localhost:8080/Files/textfile.txt"); 

      URLConnection connection = url.openConnection(); 
      connection.setDoOutput(true); 
      OutputStream outStream = connection.getOutputStream(); 
      ObjectOutputStream objectStream = new ObjectOutputStream(outStream); 
      objectStream.writeInt(637); 
      objectStream.writeObject("Hello there"); 
      objectStream.writeObject(new Date()); 
      objectStream.flush(); 
      objectStream.close(); 
     } 
     catch (Exception e) 
     { 
      System.out.println(e.toString()); 
     } 

i am unable to write text into the file(textfile.txt) . i dn't know wat the  problem is?? can anyone explain how to write data to a text file based on url information ... 
+0

可能的重複[如何使用Java從互聯網上下載和保存文件](http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-使用-java) – dogbane 2011-01-20 10:41:15

+0

那麼錯誤信息是什麼? – Satya 2011-01-20 10:42:12

+0

@Satya:沒有錯誤。剛剛執行的程序沒有任何影響 – pmad 2011-01-20 10:43:39

回答

1

要麼你需要在本地寫入文件(下載之後),然後再通過FTP上傳它。或者,如果它位於服務器上,則需要將其作爲File對象打開,然後使用BufferedWriter對其進行寫/附加操作。

try { 
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename")); 
    out.write("aString"); 
    out.close(); 
} catch (IOException e) { 
    // Handle exception 
} 

從服務器的角度來看,您需要使用絕對/相對路徑來定位文件才能寫入文件!

編輯:你可以閱讀更多關於在java HERE遠程文件訪問。

0

永遠不要使用之類的東西

System.out.println(e.toString()); 

這樣你鬆散的堆棧跟蹤和輸出發送到stdout它通常應該去到stderr。使用

e.printStackTrace(); 

代替。順便說一下,無處不在的異常是大型項目中的一個大問題,谷歌「吞食異常」以瞭解更多信息。