Java – Write a Reader to File – Java –向文件写入一个阅读器

最后修改: 2014年 8月 5日

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

In this quick tutorial, we’re going to write the contents of a Reader to a File using plain Java, then Guava and finally the Apache Commons IO library.

在这个快速教程中,我们将使用普通Java,然后是Guava,最后是Apache Commons IO库来Reader的内容写入文件

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

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

1. With Java

1.使用Java

Let’s start with the simple Java solution:

让我们从简单的Java解决方案开始。

@Test
public void givenUsingPlainJava_whenWritingReaderContentsToFile_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("Some text");

    int intValueOfChar;
    StringBuilder buffer = new StringBuilder();
    while ((intValueOfChar = initialReader.read()) != -1) {
        buffer.append((char) intValueOfChar);
    }
    initialReader.close();

    File targetFile = new File("src/test/resources/targetFile.txt");
    targetFile.createNewFile();

    Writer targetFileWriter = new FileWriter(targetFile);
    targetFileWriter.write(buffer.toString());
    targetFileWriter.close();
}

First – we’re reading the contents of the Reader into a String; then we’re simply writing the String to File.

首先–我们把阅读器的内容读成一个字符串;然后我们简单地把这个字符串写到File。

2. With Guava

2.有番石榴

The Guava solution is simpler – we now have the API to deal with writing the reader to file:

Guava的解决方案更简单–我们现在有API来处理将阅读器写入文件的问题。

@Test
public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("Some text");

    File targetFile = new File("src/test/resources/targetFile.txt");
    com.google.common.io.Files.touch(targetFile);
    CharSink charSink = com.google.common.io.Files.
      asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND);
    charSink.writeFrom(initialReader);

    initialReader.close();
}

3. With Apache Commons IO

3.使用Apache Commons IO

And finally, the Commons IO solution – also using higher level APIs to read data from the Reader and write that data to file:

最后是Commons IO解决方案–也是使用更高级别的API从Reader读取数据,并将该数据写入文件。

@Test
public void givenUsingCommonsIO_whenWritingReaderContentsToFile_thenCorrect() 
  throws IOException {
    Reader initialReader = new CharSequenceReader("CharSequenceReader extends Reader");

    File targetFile = new File("src/test/resources/targetFile.txt");
    FileUtils.touch(targetFile);
    byte[] buffer = IOUtils.toByteArray(initialReader);
    FileUtils.writeByteArrayToFile(targetFile, buffer);

    initialReader.close();
}

And there we have it – 3 simple solutions for writing the contents of a Reader to File. Make sure to check out the sample over on GitHub.

我们有了 – 3个简单的解决方案,用于将阅读器的内容写入文件。请确保查看GitHub上的样本