1

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);  
    }
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 1
    You write in file2 But close file1? – Jens Feb 01 '17 at 10:39
  • Are you sure that `name + ".txt"` results in `"file.txt"`? Why can't you use `File file1 = new File("a.txt")`? What problems did you face? – Thomas Feb 01 '17 at 10:39
  • 2
    Possible duplicate of [How to add a new line of text to an existing file in Java?](http://stackoverflow.com/questions/4614227/how-to-add-a-new-line-of-text-to-an-existing-file-in-java) – ΦXocę 웃 Пepeúpa ツ Feb 01 '17 at 10:40
  • if(!file1.exists()) file1.createNewFile() to create a new file if not existing. – Incepter Feb 01 '17 at 11:47
  • 1
    `File file1 = new File("a.txt")` does not create a physical file on the disc, it just creates an object that represents a file or directory name. – Erich Kitzmueller Feb 01 '17 at 12:01

2 Answers2

1

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 (...
user85421
  • 28,957
  • 10
  • 64
  • 87
0

I removed file1 lines with the formatter and it works although before I tried it but it wasn't creating a file. if you have similar problem and the file isn't created try file.createnewfile();

try {
    //Formatter file1 = new Formatter(name+".txt");
    File file2 = new File(name+".txt");
    // file2.createNewFile();
    fw = new FileWriter(file2,true);
    String s = Integer.toString(points);
    fw.write(s);
    fw.close();
    //file1.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}catch(Exception e){
System.out.println(e);  
}