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:
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:
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:
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}