Java Reading text files with Google Guava

Google Guava is a Java helper library which has IO tools. Here is Guava dependency for this example:
<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. The 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




Comments