HIDE NAV

Writing Out a Basic Text File

The below command line program demonstrates use of a FileWriter to create a text file and write out text data into it.

Main.java


package ceccs;

import java.io.File;
import java.io.FileWriter;

public class Main {

    public static void main(String[] args) {
        String msg = "Here's some text that you wanna save safely!\nYay!";
        String fileName = "test_file.txt";
        File file = new File(fileName);
        try {
            if (file.exists() == false) file.createNewFile();
            FileWriter fw = new FileWriter(file);
            fw.write(msg);
            fw.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }

    }
}