How do I create and write data into text file?

Here is a code example for creating text file and put some texts in it. This program will create a file called write.txt. To create and write a text file we do the following steps:

File file = new File("write.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

Below is the complete code snippet:

package org.kodejava.io;

import java.io.*;

public class WriteTextFileExample {
    public static void main(String[] args) {
        File file = new File("write.txt");

        try (Writer writer = new BufferedWriter(new FileWriter(file))) {
            String contents = "The quick brown fox" + 
                System.getProperty("line.separator") + "jumps over the lazy dog.";

            writer.write(contents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To read a text file see the following example: How do I read a text file using BufferedReader?.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.