简体   繁体   中英

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'.");}

The problem is with this line:

new FileWriter(hi).append(hello);

You're not closing the writer, which means:

  • The file handle is potentially still open, which could cause problems when you try to write to it
  • You're not flushing the writer, so the input may get lost

You should also get in the habit of using try-with-resources to acquire and then automatically close the writer, even if an exception occurs.

Personally, I'd change the structure of your code somewhat so you only open the file once:

File hi = new File("hi.txt");
boolean newFile = !hi.exists();
System.out.printf("%n%s 'hi.txt'.", newFile ? "Creating" : "Writing to");
try (Writer writer = new FileWriter(hi, true)) {
    // Note: if you've already got a string, you might as well use write...
    if (newFile) {
        writer.write("List:");
    }
    writer.write(uling);
}
catch(IOException e) {
  System.out.printf("\nError. Check the file 'hi.txt'.");
}

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

It is very important not to forget to close the writer. Well, if you do not close it, it will not be written.

writer.close().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM