Guava – Write to File, Read from File – Guava – 写入文件,从文件读取

最后修改: 2014年 10月 26日

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

1. Overview

1.概述

In this tutorial – we will learn how to write to a file and then how to read from a file using Guava IO. We will discuss how to write to file.

在本教程中,我们将学习如何使用Guava IO向文件写入和从文件读取。我们将讨论如何向文件写入。

2. Write Using Files

2.使用文件编写

Let’s start with a simple example to write a String to a file using Files:

让我们从一个简单的例子开始,使用Files将一个String写到一个文件。

@Test
public void whenWriteUsingFiles_thenWritten() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    Files.write(expectedValue, file, Charsets.UTF_8);
    String result = Files.toString(file, Charsets.UTF_8);
    assertEquals(expectedValue, result);
}

Note that we can also append to an existing file using the Files.append() API.

请注意,我们也可以使用Files.append() API来追加到一个现有的文件

3. Write to File Using CharSink

3.使用CharSink写入文件

Next – let’s see how to write a String to file using CharSink. In the following example – we get a CharSink from a file using Files.asCharSink() then use it to write:

接下来–让我们看看如何使用CharSink将一个字符串写入文件。在下面的例子中,我们使用Files.asCharSink()从文件中获得一个CharSink,然后用它来写。

@Test
public void whenWriteUsingCharSink_thenWritten() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
    sink.write(expectedValue);

    String result = Files.toString(file, Charsets.UTF_8);
    assertEquals(expectedValue, result);
}

We can also use CharSink to write multiple lines to a file. In the following example – we write a List of names and we use a space as a line separator:

我们也可以使用CharSink来向一个文件写入多行。在下面的例子中–我们写了一个List的名字,我们用空格作为行的分隔符。

@Test
public void whenWriteMultipleLinesUsingCharSink_thenWritten() throws IOException {
    List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
    File file = new File("test.txt");
    CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
    sink.writeLines(names, " ");

    String result = Files.toString(file, Charsets.UTF_8);
    String expectedValue = Joiner.on(" ").join(names);
    assertEquals(expectedValue, result.trim());
}

4. Write to File Using ByteSink

4.使用ByteSink写入文件

We can also write raw bytes using ByteSink. In the following example – we get a ByteSink from a file using Files.asByteSink() then use it to write:

我们也可以使用ByteSink写入原始字节。在下面的例子中,我们使用Files.asByteSink()从一个文件中获得一个ByteSink,然后用它来写。

@Test
public void whenWriteUsingByteSink_thenWritten() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    ByteSink sink = Files.asByteSink(file);
    sink.write(expectedValue.getBytes());

    String result = Files.toString(file, Charsets.UTF_8);
    assertEquals(expectedValue, result);
}

Note that we can move between a ByteSink and a CharSink by using the simple conversion byteSink.asCharSink().

注意,我们可以通过使用简单的转换byteSink.asCharSink()ByteSinkCharSink之间移动。

5. Read From File Using Files

5.使用Files从文件中读取

Next – let’s discuss how to Read from File Using Files.

接下来–让我们讨论如何使用文件从文件中读取。

In the following example – we read all the contents of a file using the simple Files.toString():

在下面的例子中,我们使用简单的Files.toString()读取一个文件的所有内容:

@Test
public void whenReadUsingFiles_thenRead() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    String result = Files.toString(file, Charsets.UTF_8);

    assertEquals(expectedValue, result);
}

We can also read the file into a List of lines as in the following example:

我们也可以把文件读成List行,如下面的例子。

@Test
public void whenReadMultipleLinesUsingFiles_thenRead() throws IOException {
    File file = new File("test.txt");
    List<String> result = Files.readLines(file, Charsets.UTF_8);

    assertThat(result, contains("John", "Jane", "Adam", "Tom"));
}

Note that we can use Files.readFirstLine() to read only the first line of a file.

注意,我们可以使用Files.readFirstLine()来只读一个文件的第一行。

6. Read From File Using CharSource

6.使用CharSource从文件中读取

Next – let’s see how to Read from File Using Charsource.

接下来–让我们看看如何使用Charsource从文件中读取。

In the following example – we get a CharSource from a file using Files.asCharSource() then use it to read all the file contents using read():

在下面的例子中,我们使用Files.asCharSource()从一个文件中获得一个CharSource,然后使用read()来读取所有的文件内容。

@Test
public void whenReadUsingCharSource_thenRead() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    CharSource source = Files.asCharSource(file, Charsets.UTF_8);

    String result = source.read();
    assertEquals(expectedValue, result);
}

We can also concatenate two CharSources and use them as one CharSource.

我们也可以将两个CharSource连接起来,作为一个CharSource使用。

In the following example – we read two files, the first one contains “Hello world” and the other contains “Test“:

在下面的例子中,我们读取了两个文件,第一个文件包含”Hello world“,另一个包含”Test“。

@Test
public void whenReadMultipleCharSources_thenRead() throws IOException {
    String expectedValue = "Hello worldTest";
    File file1 = new File("test1.txt");
    File file2 = new File("test2.txt");

    CharSource source1 = Files.asCharSource(file1, Charsets.UTF_8);
    CharSource source2 = Files.asCharSource(file2, Charsets.UTF_8);
    CharSource source = CharSource.concat(source1, source2);

    String result = source.read();
    assertEquals(expectedValue, result);
}

7. Read From File Using CharStreams

7.使用CharStreams从文件中阅读

Now – let’s see how to read the contents of a File into a String using CharStreams, via an intermediary FileReader:

现在–让我们看看如何使用CharStreams,通过中间的FileReader,将一个文件的内容读入String

@Test
public void whenReadUsingCharStream_thenRead() throws IOException {
    String expectedValue = "Hello world";
    FileReader reader = new FileReader("test.txt");
    String result = CharStreams.toString(reader);

    assertEquals(expectedValue, result);
    reader.close();
}

8. Read From File Using ByteSource

8.使用ByteSource从文件中阅读

We can use ByteSource to the File contents in raw byte format – as in the following example:

我们可以使用ByteSource来获取原始字节格式的文件内容–如下面的例子。

@Test
public void whenReadUsingByteSource_thenRead() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    ByteSource source = Files.asByteSource(file);

    byte[] result = source.read();
    assertEquals(expectedValue, new String(result));
}

We can also start reading bytes after specific offset using slice() as in the following example:

我们也可以使用slice()在特定的偏移量之后开始读取字节,如下例所示。

@Test
public void whenReadAfterOffsetUsingByteSource_thenRead() throws IOException {
    String expectedValue = "lo world";
    File file = new File("test.txt");
    long offset = 3;
    long len = 1000;

    ByteSource source = Files.asByteSource(file).slice(offset, len);
    byte[] result = source.read();
    assertEquals(expectedValue, new String(result));
}

Note that we can use byteSource.asCharSource() to get a CharSource view of this ByteSource.

请注意,我们可以使用byteSource.asCharSource()来获得这个ByteSourceCharSource视图。

9. Read From File Using ByteStreams

9.使用ByteStreams从文件读取

Next – let’s see how read the contents of a file into a raw byte array using ByteStreams; we will use an intermediary FileInputStream to perform the conversion:

接下来–让我们看看如何使用ByteStreams将一个文件的内容读成一个原始字节数组;我们将使用一个中间的FileInputStream来进行转换。

@Test
public void whenReadUsingByteStream_thenRead() throws IOException {
    String expectedValue = "Hello world";
    FileInputStream reader = new FileInputStream("test.txt");
    byte[] result = ByteStreams.toByteArray(reader);
    reader.close();

    assertEquals(expectedValue, new String(result));
}

10. Read Using Resources

10.阅读使用资源

Finally – let’s see how to read files that exist on the classpath – using the Resources utility as in the following example:

最后–让我们看看如何读取存在于classpath上的文件–使用Resources工具,如下例。

@Test
public void whenReadUsingResources_thenRead() throws IOException {
    String expectedValue = "Hello world";
    URL url = Resources.getResource("test.txt");
    String result = Resources.toString(url, Charsets.UTF_8);

    assertEquals(expectedValue, result);
}

11. Conclusion

11.结论

In this quick tutorial, we illustrated the various ways to read and write Files using the Guava IO support and utilities.

在这个快速教程中,我们说明了使用Guava IO支持和工具来读写文件的各种方法。

The implementation of all these examples and code snippets can be found in my Guava github project – this is an Eclipse based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现可以在我的Guava github项目中找到 – 这是一个基于Eclipse的项目,所以它应该很容易导入和运行,如实。