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

最后修改: 2014年 7月 9日

中文/混合/英文(键盘快捷键:t)

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

1.使用普通的Java

Let’s first look at the simple Java solution:

让我们先看看简单的Java解决方案。

@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

2.有番石榴

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

现在–让我们看看同样的转换,这次是使用Guava库。

@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

3.使用Commons IO

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

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

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