Write to a Text File Java

Profile picture for user arilio666

In Java, you can use the FileWriter class, which allows you to write character data to a file. As an example, consider the following:

package week1.day2;
import java.io.FileWriter;
import java.io.IOException;
public class Calculator {
    public static void main(String[] args) {
        String textToWrite = "Monkey.D.Luffy";
        try {
            FileWriter writer = new FileWriter("C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\OnePiece.txt");
            System.out.println("Successfully wrote to file.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing to file: " + e.getMessage());
  • In this example, we first create a String variable called textToWrite, which contains the text we want to write to the file.
  • We then create a FileWriter object and pass the path of the file we want to write to as a parameter.
  • Next, we call the write() method on the FileWriter object and pass our textToWrite string as a parameter.
  • This writes the contents of the string to the file.
  • Finally, we call the close() method on the FileWriter object to release any resources it may have been using and print a success message to the console.
  • Note that the FileWriter class will create a new file with the given name if one does not already exist.
  • If a file with a provided name already exists, its contents will be overwritten.
  • If appending was needed over an existing file instead of overwriting it, you could pass true as a second parameter when creating the FileWriter object.