在Java中覆盖文本文件

37

我编写的代码本应该覆盖选定文本文件的内容,但实际上却是在末尾追加内容。请问我哪里出了问题?

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
    f2 = new FileWriter(fnew,false);
    f2.write(source);
    /*for (int i=0; i<source.length();i++)
    {
        if(source.charAt(i)=='\n')
            f2.append(System.getProperty("line.separator"));
        f2.append(source.charAt(i));
    }*/
    f2.close();
} catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}           

编辑

我尝试创建一个新的temp.txt文件,并将新内容写入其中,然后删除这个文本文件并将temp.txt重命名为这个文件。问题在于,删除始终不成功。我认为我不需要改变用户权限,对吗?

此外,我程序的一部分列出了此目录中的所有文件,所以我想它们正在被程序使用,因此不能被删除。但是为什么不能覆盖写呢?

解决

这是我最大的“D'oh”时刻!我一直在Eclipse上编译它,而不是在命令提示符上执行它。因此,我的新编译类进入了bin文件夹,而通过命令提示符编译的类文件仍然在我的src文件夹中保持不变。我使用新代码重新编译,现在它工作得很好。

File fold=new File("../playlist/"+existingPlaylist.getText()+".txt");
fold.delete();
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);

try {
    FileWriter f2 = new FileWriter(fnew, false);
    f2.write(source);
    f2.close();
} catch (IOException e) {
    e.printStackTrace();
}           

2
我认为它应该可以工作。在我的情况下它是有效的。 - Rohit Jain
1
有没有任何提示可以告诉我如何删除内容? - Karthik Balakrishnan
你在那之前关闭了文件吗? - Smit
是的,在调用 delete() 之前,我已经关闭了它。 - Karthik Balakrishnan
我不知道里面发生了什么,但尝试这个。f2.write("".getBytes()); - Smit
显示剩余3条评论
6个回答

30

你的代码对我来说很好用。它按预期替换了文件中的文本,而没有追加。

如果你想追加,可以在第二个参数中进行设置。

new FileWriter(fnew,false);

变为真;


10

已解决

我最傻的时刻!我一直在Eclipse上编译它,而不是在命令提示符中执行它。因此,我的新编译类进入了bin文件夹,并且通过命令提示符编译的类文件仍然在我的src文件夹中。我使用新代码重新编译,现在它可以完美运行。

File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");

String source = textArea.getText();
System.out.println(source);

try {
    FileWriter f2 = new FileWriter(fnew, false);
    f2.write(source);
    f2.close();

} catch (IOException e) {
    e.printStackTrace();
}   

5
在初始化文件对象之后添加一行。
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();

1
new File足以创建新文件 - user813853
我只是在设置现有文件的路径。 - Karthik Balakrishnan
9
不,new File 只是创建代表文件抽象概念的Java对象。否则,在使用new File之后,将始终存在该文件,因此没有exists()方法也没有意义。 - Jim Garrison
1
@Torcellite 当然你正在设置路径,但是如果你想要覆盖,创建新文件就是一样的。 - Android Killer
@AndroidKiller。在FileWriter的第二个参数中使用false可以将追加模式设置为false。原始代码应该可以正常工作,不知道为什么它不能正常工作。在我的情况下它是可以正常工作的。 - Rohit Jain
@RohitJain 对我来说,它在Linux和Windows上也像预期的那样工作。 - nullpotent

2
自Java 11以来,更为清晰的方式是,假设您确定文件已经存在:
Files.writeString(Paths.get("path/to/file"), "str to write", StandardOpenOption.TRUNCATE_EXISTING);

如果文件不存在,上述代码将会抛出异常。

Path newFile = Paths.get("path/to/file.txt");
if(!Files.exists(newFile)) {
    Files.writeString(newFile, "some str", StandardOpenOption.CREATE);
} else {
    Files.writeString(newFile, "some str", StandardOpenOption.TRUNCATE_EXISTING);
}

检查选项的StandardOpenOption

  • CREATE - 如果文件不存在,则创建一个新文件
  • TRUNCATE_EXISTING - 如果文件已经存在并且以写入方式打开,则将其长度截断为0
  • APPEND - 将内容写入文件末尾而不是开头

等等。


1

这样简化了它,它会按照您想要的方式运行。

FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}

1
这是同样的事情。它仍在追加文本。 - Karthik Balakrishnan

1
使用公共静态字段是覆盖文本文件最简单的方法。
这会每次覆盖文件,因为您仅在第一次使用false。
public static boolean appendFile;

使用它来允许在写代码的追加字段上仅一次通过写序列,以使其为假。
// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接