Examples All in One
package guava;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.nio.charset.Charset;import java.util.List;import com.google.common.hash.HashCode;import com.google.common.hash.Hashing;import com.google.common.io.BaseEncoding;import com.google.common.io.ByteSink;import com.google.common.io.ByteSource;import com.google.common.io.Closer;import com.google.common.io.FileWriteMode;import com.google.common.io.Files;public class FilesExamples { public static void main(String[] args) throws IOException { File from = new File("from"); File to = new File("to"); // Copy File Files.copy(from, to); // Moving File Files.move(from, to); // Reading File --> ListList lines = Files.readLines(from, Charset.defaultCharset()); // Hashing File HashCode code = Files.hash(from, Hashing.md5()); // Writing & Appending Files.write("hello world ! ".getBytes(), to); Files.append("appended string", to, Charset.defaultCharset()); // Source & Sink ByteSource byteSource = Files.asByteSource(from); byte[] array = byteSource.read(); ByteSink byteSink = Files.asByteSink(to, FileWriteMode.APPEND); byteSink.write(Files.toByteArray(from)); // Copy from ByteSource --> ByteSink Files.asByteSource(from).copyTo( Files.asByteSink(to, FileWriteMode.APPEND)); // Closer // Make Sure all registered closeable object is closed // When closer.close() is called Closer closer = Closer.create(); BufferedReader reader = new BufferedReader(new FileReader(from)); BufferedWriter writer = new BufferedWriter(new FileWriter(to)); closer.register(reader); closer.register(writer); closer.close(); // Base-Encoding BaseEncoding encoding = BaseEncoding.base64(); encoding.encode(Files.toByteArray(from)); }}