Java 如何基于url将数据写入文件?
您需要在本地(下载后)写入文件,然后通过FTP再次上传。或者,如果它位于您的服务器上,您需要将其作为Java 如何基于url将数据写入文件?,java,url,filewriter,Java,Url,Filewriter,您需要在本地(下载后)写入文件,然后通过FTP再次上传。或者,如果它位于您的服务器上,您需要将其作为文件对象打开,然后使用缓冲写入器对其进行写入/追加 try { URL url = new URL("http://localhost:8080/Files/textfile.txt"); URLConnection connection = url.openConnection(); connection.
文件
对象打开,然后使用缓冲写入器
对其进行写入/追加
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 ...
您需要从服务器的角度使用绝对/相对路径来定位文件,以便对其进行写入
编辑:您可以阅读有关java远程文件访问的更多信息 永远不要使用这样的东西
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
// Handle exception
}
通过这种方式,您可以释放堆栈跟踪,并将输出发送到stdout,通常应该发送到stderr。使用
System.out.println(e.toString());
相反。顺便说一句,不必要地到处捕捉异常是大型程序中的一个大问题,谷歌搜索“吞咽异常”以了解更多信息。可能重复@Satya:无错误。只执行了程序,没有任何错误effect@T:如何处理它?pmad:接受问题的答案。:)文件位于服务器及其基于java的应用程序中。我们如何获取其他系统(可能是或可能是服务器)的路径?你好,maaartinus!这应该是一个评论,因为它没有直接回答问题。尽管如此,一个很好的建议是:)当然,但在写这篇文章的时候,我还没有被允许写评论。我选择写它,因为糟糕的异常处理/报告是初学者最可怕的错误之一。下次,我会把它做好;我是新来的。
e.printStackTrace();