One of the most common tasks while creating a software application is to read and write data to a file. The data could be stored in a JSON file, a CSV file, a binary file, or in a text file.

In this article, you'll learn how to read and write text and binary files in Java. Java provides several APIs (unknown as Java I/O) for reading and writing files right from the beginning. Over the years, these APIs are further improved to provide a simplified and robust interface for dealing with different kinds of files.

Reading Text Files in Java

If you want to read a simple text file, just use the FileReader class and wrap it in a BufferedReader. Here is an example that uses the BufferedReader class to read a file named input.txt line by line:

try {
    // create a reader
    BufferedReader br = new BufferedReader(new FileReader("input.txt"));

    // read until end of file
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    // close the reader
    br.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

Check out how to read a file line by line in Java tutorial for more examples.

Reading Binary Files in Java

If you want to read a binary file or a file containing special characters, you need to use the FileInputStream class instead of FileReader. Here is an example:

try {
    // create a reader
    FileInputStream fis = new FileInputStream(new File("input.dat"));

    // read until end of file
    int ch;
    while ((ch = fis.read()) != -1) {
        System.out.print((char) ch);
    }

    // close the reader
    fis.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

Writing Text Files in Java

To write a text file in Java, you should use the FileWriter class and wrap it in a BufferedWriter as shown below:

try {
    // create a writer
    BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));

    // write text to file
    bw.write("Hey, there!");
    bw.newLine();
    bw.write("See you soon.");

    // close the writer
    bw.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will create a new file named output.txt with the following contents:

Hey, there!
See you soon.

Writing Binary Files in Java

You can easily create and write to a binary file in Java by using the FileOutputStream class. Here is an example that creates a new binary file and writes data into it:

try {
    // create a writer
    FileOutputStream fos = new FileOutputStream(new File("output.dat"));

    // write data to file
    fos.write("Hey, there!".getBytes());
    fos.write("\n".getBytes());
    fos.write("See you soon.".getBytes());

    // close the writer
    fos.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.