Java FileWriter 覆盖
我有一段代码,只要有新数据可用作 InputStream ,就会生成新数据。每次都会覆盖同一个文件。有时文件在写入之前就变成了 0 kb。 Web 服务定期读取这些文件。我需要避免文件为 0 字节的情况。
它是如何做到这一点的?在这种情况下锁会有帮助吗?如果浏览器读取锁定的文件,浏览器是否会继续显示缓存中的旧数据,直到锁定被释放并且文件可以再次读取。
try{
String outputFile = "output.html";
FileWriter fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
outputFile = "anotheroutput.html";
fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
fWriter.close();
}
catch(Exception e)
{
e.prinStackTrace();
}
I have a piece of code that generates new data whenever there is new data available as InputStream . The same file is overwritten everytime. Sometimes the file becomes 0 kb before it gets written. A webservice reads these files at regular intervals. I need to avoid the case when the file is 0 bytes.
How do it do this? Will locks help in this case? If the browser comes in to read a file which is locked, will the browser continue to show old data from the cache until the lock is released and file is available to be read again.
try{
String outputFile = "output.html";
FileWriter fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
outputFile = "anotheroutput.html";
fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
fWriter.close();
}
catch(Exception e)
{
e.prinStackTrace();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试写入临时文件(在同一文件系统中),文件写入完成后,使用 File.renameTo() 将其移动到位。如果您的底层文件系统支持原子移动操作(大多数都支持),那么您应该获得所需的行为。如果您在 Windows 上运行,则必须确保在读取后关闭文件,否则文件移动将失败。
Try writing to a temporary file (in the same file system) and once the file write is complete move it into place using File.renameTo(). If you underlying file system supports atomic move operations (most do) then you should get the behaviour that you require. If you are running on windows you will have to make sure you close the file after reading otherwise the file move will fail.
尝试使用上面的:-)
try using above :-)
你的要求不是很明确。您想每次都写入一个新名称文件,还是想附加到同一个文件,或者想覆盖同一个文件?无论如何,这三种情况都很简单,您可以通过 API 进行管理。
如果问题是 Web 服务正在读取尚未完成的文件,即处于写入阶段。在您的网络服务中,您应该检查该文件是否是只读的,然后只有您读取该文件。在写入阶段,写入完成后将文件设置为只读。
出现 0Kb 文件是因为您再次覆盖同一个文件。覆盖会清除所有数据,然后开始写入新内容。
Your requirement is not very clear. Do you want to write a new name file every time or you want to append to the same file or you want to over write the same file? Anyway all three cases are easy and from the API you can manage it.
If the issue is that a web service is reading the file which is not yet complete i.e. is in writing phase. In your web service you should check if the file is read only, then only you read the file. In writing phase once writing is finished set the file to read only.
The 0Kb file happens because you are overwriting the same file again. Overwriting cleans up all the data and then start writing the new content.
这是不需要的:
那是因为对文件的操作是 Data 类的方法
this is not needed:
that's because work on the file is a method of class Data