2

只要有新数据作为 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();
}
4

4 回答 4

2

尝试写入临时文件(在同一文件系统中),一旦文件写入完成,使用 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();
       }
   }
}
于 2009-10-24T06:59:45.750 回答
1
FileWriter fWriter = new FileWriter(fileName,true);

尝试使用上面:-)

于 2010-12-18T09:36:56.553 回答
0
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();

那是因为对文件的工作是 Data 类的一种方法

于 2009-10-24T02:41:08.347 回答
0

你的要求不是很清楚。你想每次都写一个新的名称文件,或者你想追加到同一个文件,或者你想覆盖同一个文件?无论如何,这三种情况都很简单,您可以通过 API 管理它。

如果问题是 Web 服务正在读取尚未完成的文件,即处于写入阶段。在您的 Web 服务中,您应该检查该文件是否为只读,然后只有您读取该文件。在写入阶段,一旦写入完成,将文件设置为只读。

发生 0Kb 文件是因为您再次覆盖同一个文件。覆盖清除所有数据,然后开始写入新内容。

于 2009-10-24T02:47:46.040 回答