Always use a try-with-resources statement to automatically close files and conserve resources.
Source Code
try (FileWriter writer = new FileWriter("filename.txt")) {
writer.write("Hello, Java!");
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}