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!

1 comment:

  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    or learn thru JavaScript Online Training from India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

    ReplyDelete