Java FileWriter 覆盖

标签 java synchronization overwrite 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();
}

最佳答案

尝试写入临时文件(在同一文件系统中),文件写入完成后,使用 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/

相关文章:

java - MongoDB 3,java驱动,全文检索,如何?

java - 即使使用close关闭spring上下文,为数据库连接创建的TimerThreads仍继续运行

Java 用流结果覆盖文件

css - 具有绝对定位的 <span> 的 div 会覆盖下一个 <div>

在客户端/服务器之间同步文本的算法

java - 如何覆盖现有文件?

java - 非阻塞套接字客户端和选择器

java - Centos 7上Java无法加载系统游标: CopyDrop. 32x32异常

java - 经典的 Java 同步问题(愿意试一试吗?)

database - 同步来自不同应用程序的数据实体