File to Reader conversion in Java

May 16, 2020 No comments Java IO Conversions File Reader

1. Introduction

In this article, we will present several ways to convert File to Reader using plain Java, Guava, and Apache Commons IO library.

Looking for more useful articles about Java IO? Check the following links:

2. Convert File to Reader using plain Java

Let's start with the plain Java approach:

package com.frontbackend.java.io.conversions.toreader.fromfile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

public class FileToReaderUsingFileReader {

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("/tmp/input.txt");

        Reader reader = new FileReader(file);
    }
}

In pure Java, we have a dedicated class that will straightforwardly do the conversion - FileReader.

3. File to Reader conversion using Guava library

To convert File to Reader we can also use Guava library that provides a single-line solution:

package com.frontbackend.java.io.conversions.toreader.fromfile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

import com.google.common.io.Files;

public class FileToReaderUsingGuava {

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("/tmp/input.txt");

        Reader reader = Files.newReader(file, StandardCharsets.UTF_8);
    }
}

In this example, we are making use of the Files.newReader(..) method that creates Reader instance taking File as a parameter.

4. Convert File to Reader using Apache Commons IO library

Another library we can use in such conversion is Apache Commons IO. Let's take a look at a solution using that library:

package com.frontbackend.java.io.conversions.toreader.fromfile;

import java.io.File;
import java.io.IOException;
import java.io.Reader;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.input.CharSequenceReader;

public class FileToReaderUsingFileUtils {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/input.txt");

        byte[] bytes = FileUtils.readFileToByteArray(file);
        Reader reader = new CharSequenceReader(new String(bytes));
    }
}

In this example, first, we need to read bytes from the File using FilesUtils.readFileToByteArray(...) method. Then, CharSequenceReader creates Reader implementation.

5. Conclusion

This article covered several ways to convert File to Reader using pure Java and libraries such as Guava and Apache Commons IO. It is the programmer's decision which solution to choose. If we do not want to include additional dependencies into our project we can simply use solutions available in plain Java.

Examples used in this article are available under our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}