Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

In this quick tutorial we're going to illustrate how to convert a File to a Reader using plain Java, Guava or Apache Commons IO. Let's get started.

This article is part of the “Java – Back to Basic” series here on Baeldung.

1. With Plain Java

Let's first look at the simple Java solution:

@Test
public void givenUsingPlainJava_whenConvertingFileIntoReader_thenCorrect() 
  throws IOException {
    File initialFile = new File("src/test/resources/initialFile.txt");
    initialFile.createNewFile();
    Reader targetReader = new FileReader(initialFile);
    targetReader.close();
}

2. With Guava

Now – let's see the same conversion, this time using the Guava library:

@Test
public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws 
  IOException {
    File initialFile = new File("src/test/resources/initialFile.txt");
    com.google.common.io.Files.touch(initialFile);
    Reader targetReader = Files.newReader(initialFile, Charset.defaultCharset());
    targetReader.close();
}

3. With Commons IO

And finally, let's end with the Commons IO code sample, doing the conversion via an intermediary byte array:

@Test
public void givenUsingCommonsIO_whenConvertingFileIntoReader_thenCorrect() 
  throws IOException {
    File initialFile = new File("src/test/resources/initialFile.txt");
    FileUtils.touch(initialFile);
    FileUtils.write(initialFile, "With Commons IO");
    byte[] buffer = FileUtils.readFileToByteArray(initialFile);
    Reader targetReader = new CharSequenceReader(new String(buffer));
    targetReader.close();
}

And there we have it – 3 ways to convert a File into a Reader – first with plain Java, then with Guava and finally with the Apache Commons IO library. Make sure to check out the sample over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!