我有一段代码,只要有新数据可用作 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();
}
最佳答案
尝试写入临时文件(在同一文件系统中),文件写入完成后,使用 File.renameTo() 将其移动到位。如果您的底层文件系统支持原子移动操作(大多数都支持),那么您应该获得所需的行为。如果您在 Windows 上运行,则必须确保在读取后关闭文件,否则文件移动将失败。
public class Data
{
private final File file;
protected Data(String fileName) {
this.file = new File(filename);
}
/* above is in some class somehwere
* then your code brings new info to the file
*/
//
public synchronized accessFile(String data) {
try {
// Create temporary file
String tempFilename = UUID.randomUUID().toString() + ".tmp";
File tempFile = new File(tempFilename);
//write the data ...
FileWriter fWriter = new FileWriter(tempFile);
fWriter.write(data);
fWriter.flush();
fWriter.close();
// Move the new file in place
if (!tempFile.renameTo(file)) {
// You may want to retry if move fails?
throw new IOException("Move Failed");
}
} catch(Exception e) {
// Do something sensible with the exception.
e.prinStackTrace();
}
}
}
关于Java FileWriter 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1616746/