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();
        }
    }
}

How do I read a text file?

The code snippet below is an example of how to read a text file. This program will read a file called test.txt and shows its content.

package org.kodejava.example.io;

import java.io.*;

public class ReadTextFileExample {
    public static void main(String[] args) {
        File file = new File("/Users/wsaryada/kodejava/test.txt");

        try (BufferedReader reader =
                     new BufferedReader(new FileReader(file))) {
            StringBuilder contents = new StringBuilder();

            String text = null;
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(
                        System.getProperty("line.separator"));
            }

            System.out.println(contents.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

You can also try to use the following example to read a file, How do I read text file content line by line using commons-io?.