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.

package org.kodejava.example.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();
        }
    }
}

Wayan Saryada

A programmer, a slow runner, a recreational open water diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply