How to Write to a File in Java


In this example we will show the method to write to a file in Java.

Source Code

package com.beginner.examples;

import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {
  public static void main(String[] args) {
    try {
      FileWriter writer = new FileWriter("example.txt");
      writer.write("test"); // write to a file
      writer.close();
      System.out.println("Success!");
    } catch (IOException e) {
      System.out.println("Error!");
      e.printStackTrace();
    }
  }
}

Output:

Success!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments