Basic File Writing with FileWriter in Java


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();
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments