How to create a text file and write into it using java code

This java program will create a new text file in the specified location and also will write the String content to the file.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CreateAndWriteToTextFile {
    public static void main(String[] args) {
        try {
            String content = "This is the test line which will be eventually written to the text file."
                    + "\n This is other Test line.";
            File file = new File("/Users/Amzi/Amzi.txt");
            // Checks if the file already exists or not
            if (!file.exists())
                file.createNewFile();

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            System.out.println("Content is written to the file!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

Content is written to the file!

No comments:

Post a Comment