在java中覆盖txt文件

我写的代码应该覆盖所选文本文件的内容,但它会附加它。 我究竟做错了什么?

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’哦”时刻! 我一直在Eclipse而不是cmd上编译它,这是我执行它的地方。 所以我新编译的类转到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(); } 

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

如果要追加,请在其中设置第二个参数

 new FileWriter(fnew,false); 

为真;

初始化文件对象后再添加一行

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

解决了

我最大的“D’哦”时刻! 我一直在Eclipse而不是cmd上编译它,这是我执行它的地方。 所以我新编译的类转到bin文件夹,通过命令提示符编译的类文件在我的src文件夹中保持不变。 我用我的新代码重新编译,它就像一个魅力。

  File fold=new File("../playlist/"+existingPlaylist.getText()+".txt"); fold.delete(); //File temp=new File("../playlist/temp.txt"); File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt"); String source = textArea.getText(); System.out.println(source); /*FileWriter f2; PrintWriter pw; try { f2 = new FileWriter(fnew,false); pw= new PrintWriter(f2); f2.write(source); /*for (int i=0; i 

这样可以简化它,并且它可以按照您的需要运行。

 FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt"); try { f.write(source); ... } catch(...) { } finally { //close it here } 

覆盖文本文件的最简单方法是使用公共静态字段。

这将每次都覆盖文件,因为你的第一次使用时只会使用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(); }