Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting txt file in java

The code I've written is supposed to overwrite over the contents of the selected text file, but it's appending it. What am I doing wrong exactly?

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(); }            

EDIT

I tried making a new temp.txt file and writing the new contents into that, deleting this text file and renaming temp.txt to this one. Thing is, the deletion is always unsuccessful. I don't think I have to change user permissions for this do I?

Also, a part of my program lists all the files in this directory, so I'm guessing they're being used by the program and so can't be deleted. But why not overwritten?

SOLVED

My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.

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(); }            
like image 603
Karthik Balakrishnan Avatar asked Dec 05 '12 18:12

Karthik Balakrishnan


1 Answers

Your code works fine for me. It replaced the text in the file as expected and didn't append.

If you wanted to append, you set the second parameter in

new FileWriter(fnew,false); 

to true;

like image 68
user1757442 Avatar answered Oct 14 '22 02:10

user1757442