我们如何根据 url 将数据写入文件?
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 ...
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 ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在本地写入文件(下载后),然后再次通过 FTP 上传。或者,如果它位于您的服务器上,您需要将其作为
File
对象打开,然后使用BufferedWriter
写入/附加到它。您需要从服务器的角度使用绝对/相对路径来定位文件才能写入!
编辑:您可以阅读有关java中远程文件访问的更多信息此处。
Either you need to write to the file locally (after downloading it) and then upload it via FTP again. Or if it's located on your server, you need to open it as a
File
object and then write/append to it with aBufferedWriter
for example.You need to use the absolute/relative path from your server's point of view to locate the file in order to write to it!
EDIT: You can read more about remote file access in java HERE.
永远不要使用类似
这样的东西,这样你就会丢失堆栈跟踪,并且输出会转到标准输出,而通常应该转到标准错误。 代替使用
。顺便说一句,在更大的程序中,不必要地到处捕获异常是一个大问题,谷歌搜索“吞噬异常”以了解更多信息。
Never ever use things like
This way you loose the stack trace and the output goes to stdout where it normally should go to stderr. Use
instead. Btw., needlessly catching exceptions everywhere is a big problem in bigger programs, google out "swallowing exceptions" to learn more.