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:
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'.");
}
See more on this question at Stackoverflow