Java – File to Reader – Java –文件到阅读器

最后修改: 2014年 7月 9日


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.

在这个快速教程中,我们将说明如何使用普通Java、Guava或Apache Commons IO将文件转换为阅读器。让我们开始吧。

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

本文是Baeldung网站上“Java – Back to Basic “系列的一部分。

1. With Plain Java


Let’s first look at the simple Java solution:


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

2. With Guava


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


public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws 
  IOException {
    File initialFile = new File("src/test/resources/initialFile.txt");;
    Reader targetReader = Files.newReader(initialFile, Charset.defaultCharset());

3. With Commons IO

3.使用Commons IO

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

最后,让我们以Commons IO的代码样本结束,通过一个中间字节数组进行转换。

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

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,然后是Guava,最后是Apache Commons IO库。请务必查看GitHub上的样本