DEV Community

Cover image for Examples using FileReader and FileWriter to read and write plain text
Yongchang He
Yongchang He

Posted on • Updated on

Examples using FileReader and FileWriter to read and write plain text

This blog is to demonstrate a simple way to use IO stream FileReader and FileWriter.

we can use FileReader to read text from an existing file(read in character), and print text in the terminal; use FileWriter to write content to certain file. the file will be created if it doesn't exist in the current directory.

One thing to remember, if we use IDEA, we should create a file named "temp.txt" with some words in the root directory of the current project when we use FileReader to read from the file.

Demo of FileReader

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderTest01 {
    public static void main(String[] args) {
        // Create FileReader object
        FileReader fr = null;
        try {
            fr = new FileReader("temp.txt");
            char[] chars = new char[4];

            int readCount = 0;
            // Keep reading until reaching the last word
            while ((readCount = fr.read(chars)) != -1) {
                System.out.print(new String(chars, 0, readCount));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    // close the stream
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Demo of FileWriter

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterTest01 {
    public static void main(String[] args) {
        // create FileWriter object fw
        FileWriter fw = null;
        try {
            // the file will be created if it does not exist
            fw = new FileWriter("file",true);
            // can run multiple times, and observe the results
            fw.write("Hello Java ");
            // do not forget to flush
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fw != null) {
                try {
                    // remember to close the stream
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)