Master Google Guava I/O Utilities for Faster, Cleaner Java File Handling
The article explains how Guava’s ByteStreams, CharStreams, and Files classes simplify Java I/O by offering static methods for reading, writing, copying, and transforming byte and character streams, and demonstrates practical code examples—including basic stream handling, Java 8 stream integration, and temporary file management—to improve development efficiency.
Java’s standard I/O APIs are powerful but often verbose; Guava supplies a set of static utility classes that streamline common byte‑ and character‑stream operations.
ByteStreams and CharStreams
ByteStreams focuses on InputStream and OutputStream handling, offering methods such as toByteArray(InputStream) and write(byte[] data, OutputStream). CharStreams targets Reader and Writer, providing toString(Reader) and write(CharSequence data, Writer). Both classes expose a collection of static helpers for reading, writing, copying, and converting streams.
Basic example using ByteStreams, CharStreams and Files
The following program reads a file into a byte array, converts it to a UTF‑8 string, transforms the text to upper case, and writes the result back using Guava utilities.
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import java.io.*;
public class GuavaIOExample {
public static void main(String[] args) {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try {
// Read bytes from file
byte[] fileContentBytes = Files.toByteArray(inputFile);
// Convert to string with UTF‑8
String fileContent = new String(fileContentBytes, Charsets.UTF_8);
// Transform content
String processedContent = fileContent.toUpperCase();
// Write bytes back
byte[] processedBytes = processedContent.getBytes(Charsets.UTF_8);
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
ByteStreams.write(processedBytes, outputStream);
}
System.out.println("File processed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
// Alternative using Guava streams
public static void mainWithGuavaStreams(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (FileInputStream fileInputStream = new FileInputStream(inputFile);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, Charsets.UTF_8);
// Transform each character to upper case
InputStreamReader transformedReader = new InputStreamReader(
new TransformingInputStream(inputStreamReader, character -> (char) Character.toUpperCase(character)),
Charsets.UTF_8);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, Charsets.UTF_8)) {
CharStreams.copy(transformedReader, outputStreamWriter);
System.out.println("File processed successfully with Guava streams.");
}
}
// Simple TransformingInputStream used above
private static class TransformingInputStream extends java.io.InputStream {
private final InputStreamReader reader;
private final java.util.function.IntFunction<Integer> transformer;
public TransformingInputStream(InputStreamReader reader, java.util.function.IntFunction<Integer> transformer) {
this.reader = reader;
this.transformer = transformer;
}
@Override
public int read() throws IOException {
int character = reader.read();
if (character == -1) {
return -1;
}
return transformer.apply(character);
}
@Override
public void close() throws IOException {
reader.close();
}
}
}More concise version with Files.asCharSource / asCharSink
Guava’s Files.asCharSource and Files.asCharSink combine with Java 8 streams to read, transform, and write text in a few lines.
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class GuavaIOExamplePractical {
public static void main(String[] args) {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try {
String content = Files.asCharSource(inputFile, Charsets.UTF_8).read();
String upperCaseContent = content.chars()
.mapToObj(c -> (char) c)
.map(String::valueOf)
.map(String::toUpperCase)
.reduce((a, b) -> a + b)
.orElse("");
Files.asCharSink(outputFile, Charsets.UTF_8).write(upperCaseContent);
System.out.println("File processed successfully with Guava and Java 8 streams.");
} catch (IOException e) {
e.printStackTrace();
}
}
}Files utility class
The Files class also offers methods for temporary file creation, copying, and deletion. The example below creates a temporary file, writes sample text, reads it back, copies it to a new file, and finally deletes the temporary file.
import com.google.common.io.Files;
import com.google.common.base.Charsets;
import java.io.File;
import java.io.IOException;
public class GuavaFilesExample {
public static void main(String[] args) {
File tempFile = null;
try {
tempFile = Files.createTempFile("guava_example", ".txt");
System.out.println("Temporary file created: " + tempFile.getAbsolutePath());
Files.asCharSink(tempFile, Charsets.UTF_8).write("这是一些示例文本.");
System.out.println("Data written to file.");
String content = Files.asCharSource(tempFile, Charsets.UTF_8).read();
System.out.println("Read content: " + content);
File newFile = new File("new_guava_example.txt");
Files.copy(tempFile, newFile);
System.out.println("File copied to: " + newFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (tempFile != null && !tempFile.delete()) {
System.out.println("Failed to delete temporary file.");
} else {
System.out.println("Temporary file deleted successfully.");
}
}
}
}These examples show how Guava’s I/O helpers reduce boilerplate, improve readability, and enable concise handling of common file‑processing scenarios in Java.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
