Overwriting txt file in java
Asked Answered
J

6

38

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();
}           
Jumbala answered 5/12, 2012 at 18:8 Comment(8)
I think it should work. It's working in my case.Satisfy
Its working in my case too. May be something weird happening in your program. Try to work around the problem. Delete the whole content first and then start writing new content to same file.Laplante
Any hints on how I can delete the content?Jumbala
fnew.delete(); This should do the trick.Laplante
Tried that. Set it to a boolean variable. It's always false :\Jumbala
Did you closed your file before that?Laplante
Yeah, I closed it before calling delete()Jumbala
I dont know whats going on in there. but try this. f2.write("".getBytes());Laplante
J
10

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();
}   
Jumbala answered 6/12, 2012 at 0:48 Comment(0)
F
30

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;

Forwardness answered 5/12, 2012 at 18:22 Comment(0)
J
10

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();
}   
Jumbala answered 6/12, 2012 at 0:48 Comment(0)
C
5

Add one more line after initializing file object

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
Chemism answered 5/12, 2012 at 18:14 Comment(6)
new File is sufficient to Create a new fileTaimi
I'm just setting path to an existing file.Jumbala
@ALJIMohamed no, new File just creates the Java object representing an abstract concept of a file. Otherwise, there would be no point in having an exists() method as the file would always exist after new File.Loutitia
@Torcellite yes ofcourse you are setting path, but as you want to overrtite, it's same to create new file.Chemism
@AndroidKiller. Using false as 2nd parameter to FileWriter sets the append mode to false. The original code in OP should work. Don't know why it isn't working. It's working in my case.Satisfy
@RohitJain It works on Linux and Windows for me as expected, too.Guanajuato
E
3

A much cleaner way since Java 11, assuming you're sure that the file already exists:

Files.writeString(Paths.get("path/to/file"), "str to write", StandardOpenOption.TRUNCATE_EXISTING);

The above will throw if the file doesn't exist. In that case:

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

Check the StandardOpenOption for options:

  • CREATE - Create a new file if it does not exist
  • TRUNCATE_EXISTING - If the file already exists and it is opened for WRITE access, then its length is truncated to 0
  • APPEND - write to the end of the file rather than the beginning

etc.

Ellen answered 7/3, 2023 at 18:47 Comment(0)
G
1

This simplifies it a bit and it behaves as you want it.

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

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}
Guanajuato answered 5/12, 2012 at 18:19 Comment(1)
It's the same thing. It's still appending textJumbala
P
1

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// 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();
 }           
Plumbum answered 26/1, 2017 at 1:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.