Search code examples
javafilewriter

Filewriter will not append text to newly created file


I'm fairly new to Java. I was trying to add "List:" to the beginning of a new text file if it doesn't exist. Instead, the text file is blank, with the input below a line of blank space.

File hi = new File("hi.txt");
try{
  if(!hi.exists()){
    System.out.printf("\nCreating 'hi.txt'."); 
    hi.createNewFile();
    String hello = "List:";
    new FileWriter(hi).append(hello);
  }
  else{
    System.out.printf("\nWriting to 'hi.txt'");
  }
  FileWriter writeHere = new FileWriter(hi, true);
  String uling = "hi";
  writeHere.append(uling);
  writeHere.close();
}
//error catching
catch(IOException e){
  System.out.printf("\nError. Check the file 'hi.txt'.");}

Solution

  • Pass true as a second argument to FileWriter to turn on "append" mode (in the first FileWriter you have created).

    Also, you should create the variable FileWriter, and close it after appending "List:", as you leave the scope of that variable.

    So, I would edit the code as following:

    File hi = new File("hi.txt");
    try {
        if (!hi.exists()) {
            System.out.printf("\nCreating 'hi.txt'.");
            hi.createNewFile();
            String hello = "List:";
            FileWriter writer = new FileWriter(hi, true);
            writer.append(hello);
            writer.close();
        } else {
            System.out.printf("\nWriting to 'hi.txt'");
        }
        FileWriter writeHere = new FileWriter(hi, true);
        String uling = "hi";
        writeHere.append(uling);
        writeHere.close();
    }
    //error catching
    catch (IOException e) {
        System.out.printf("\nError. Check the file 'hi.txt'.");
    }
    

    NOTICE: Modifications at lines 7-9.

    http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html