Skip to content

Java Reading text files with Google Guava

Ramesh Fadatare edited this page Jul 11, 2019 · 1 revision

Google Guava is a Java helper library which has IO tools, too. Similar to the above Apache commons methods the following two Guava methods would consume a lot of system resources if the file to be read is very large.

We have used this dependency for the following two projects.

<dependencies>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>19.0</version>
    </dependency>

</dependencies>

Java Reading text files with Google Guava

In the example, we read all of the lines from a file with the Files.readLines() method. The method returns a list of strings. A default charset is specified as the second parameter.

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ReadTextFileEx8 {
    
    public static void main(String[] args) throws IOException {
        
        String fileName = "src/main/resources/thermopylae.txt";
        
        List<String> lines = Files.readLines(new File(fileName), 
                Charsets.UTF_8);
        
        StringBuilder sb = new StringBuilder();
        
        for (String line: lines) {
            sb.append(line);
            sb.append(System.lineSeparator());
        }
        
        System.out.println(sb);
    }
}

In the second example, we read the file contents into a string.

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class ReadTextFileEx9 {

    public static void main(String[] args) throws IOException {

        String fileName = "src/main/resources/thermopylae.txt";

        String content = Files.toString(new File(fileName), Charsets.UTF_8);

        System.out.println(content);
    }
}

The Files.toString() method reads all characters from a file into a string, using the given character set.

Clone this wiki locally