我有一段代码,只要有新数据可以作为InputStream使用,它就会生成新数据。每次都会覆盖相同的文件。有时,文件在写入之前就会变成0kb。webservice服务定期读取这些文件。我需要避免当文件是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();
}发布于 2009-10-24 14:59:46
尝试写入一个临时文件(在同一文件系统中),完成文件写入后,使用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();
}
}
}发布于 2010-12-18 17:36:57
FileWriter fWriter = new FileWriter(fileName,true);尝试使用上面的:-)
发布于 2009-10-24 10:41:08
public class Data
{
String fileName;
protected Data(String fileName)
{
this.fileName= fileName;
return; // return from constructor often not needed.
}
/* above is in some class somehwere
* then your code brings new info to the file
*/
//
public synchronized accessFile(String data)
{
try
{
// File name to be class member.
FileWriter fWriter = new FileWriter(fileName);
//write the data ...
fWriter.write(data);
fWriter .flush();
fWriter .close();
return;
}
catch(Exception e)
{
e.prinStackTrace();
}这不是必需的:
outputFile = "anotheroutput.html";
fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
fWriter.close();这是因为处理文件是类数据的一种方法
https://stackoverflow.com/questions/1616746
复制相似问题