2011-01-20 38 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(); 

代替。顺便说一下,无处不在的异常是大型项目中的一个大问题,谷歌“吞食异常”以了解更多信息。