【问题标题】:Unable to append to file based on file.length() operation无法根据 file.length() 操作附加到文件
【发布时间】:2020-08-30 13:22:12
【问题描述】:

我想追加到文件,如果它不为空;如果它是空的,就想写。下面是我的代码。 write 函数有效, append 无效。有人可以在这里指导吗?

public class Filecreate {
public static void main(String args[]) throws IOException {
    File file = new File("newFileCreated.txt");
    System.out.println("file path "+file.getAbsolutePath() +" file length - "+file.length());
    FileWriter myWriter = new FileWriter(file);
    if((int)file.length() != 0){
        myWriter.append("appended text\n");
    }else{
        myWriter.write("Files in Java might be tricky, but it is fun enough!");
    }
    myWriter.close();
    System.out.println("file length after writing to file "+file.length());
}

}

【问题讨论】:

    标签: java file


    【解决方案1】:

    您无需担心文件是否包含任何内容。只需将 true 的参数应用于 FileWriter 构造函数中的 append 参数,然后始终使用 Writer#append() 方法,例如:

    String ls = System.lineSeparator();
    String file = "MyFile.txt";
    
    FileWriter myWriter = new FileWriter(file, true)
    myWriter.append("appended text" + ls);
    
    /* Immediately write the stream to file. Only really 
       required if the writes are in a loop of some kind 
       and you want to see the write results right away. 
       The close() method also flushes the stream to file 
       before the close takes place.  */
    myWriter.flush();   
    
    System.out.println("File length after writing to file " + 
                       new File(file).length());
    myWriter .close();
    
    • 如果文件不存在,它将被自动创建 以及附加到它的行。
    • 如果文件已创建但为空,则将该行附加到该文件。
    • 如果文件确实包含内容,则该行仅附加到 该内容。

    【讨论】:

    • 它与真正的论点一起工作。但是 append 和 write 的工作方式相同。当我们对filewriter使用true时,append和write之间没有区别吗?
    • Peter Lawreythis SO Answer Post 中解释得很好。
    【解决方案2】:

    出现此问题是因为您在打开文件后测量文件的大小。因此,您必须在打开文件之前检查文件的大小。另外,我不建议将 long 转换为 int,因为您的解决方案不适用于大文件。总之,以下代码将为您工作:

        public static void main(String[] args) throws IOException {
        File file = new File("newFileCreated.txt");
        long fileSize = file.length();
        System.out.println("file path "+file.getAbsolutePath() +" file length - "+file.length());
        FileWriter myWriter = new FileWriter(file);
    
        if(fileSize > 0L){
            myWriter.append("appended text\n");
        }else{
            myWriter.write("Files in Java might be tricky, but it is fun enough!");
        }
        myWriter.close();
        System.out.println("file length after writing to file "+file.length());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 2019-10-05
      • 2015-11-25
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 2022-12-18
      相关资源
      最近更新 更多