Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

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.

2. Write Using Files

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

@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.

3. Write to File Using 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:

@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:

@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

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:

@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().

5. Read From File Using 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():

@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:

@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.

6. Read From File Using CharSource

Next – let’s see how to Read from File Using 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():

@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.

In the following example – we read two files, the first one contains “Hello world” and the other contains “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

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

@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

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

@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:

@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.

9. Read From File Using 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:

@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

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

@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

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

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.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!