Search code examples
javafileoverwritefilewriter

filewriter overwriting the file


I am trying to make filewriter append instead of overwrite by using FileWriter("file.txt",true) but it is not working , also another problem (not sure if realted) is that I can't use File file1 = new File("a.txt") to create a file so I am using formatter. Note I am a beginner so please elaborate the mistakes I did if possible.

public static void newPlayer(){
    String name = JOptionPane.showInputDialog("Write yourn name ","new player");
    System.out.println(name +" " +points);
    try {
        Formatter file1 = new Formatter(name+".txt");
        File file2 = new File(name+".txt");
        fw = new FileWriter(file2,true);
        String s = Integer.toString(points);
        fw.write(s);
        fw.close();
        file1.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(Exception e){
        System.out.println(e);  
    }
}

Solution

  • Remove the two lines regarding file1, it's not being used anyways.

    Using the Formatter is opening the file with append=false, which is interfering with the settings from FileWriter (same file descriptor being used under the hood? OS dependent?).

    ...
    try {
        File file2 = new File(name+".txt");
        FileWriter fw = new FileWriter(file2,true);
        String s = Integer.toString(points);
        fw.write(s);  
        // a line feed would make the file more readable
        fw.close();
    } catch (...