Created
November 23, 2011 23:19
-
-
Save KengoTODA/1390221 to your computer and use it in GitHub Desktop.
a sample code to explain how to use FileBackedOutputStream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package guava.io; | |
import java.io.BufferedOutputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import com.google.common.base.Stopwatch; | |
import com.google.common.io.FileBackedOutputStream; | |
public class FileBackedOutputStreamSample { | |
private static final int KB = 1024; | |
private static final int MB = 1024 * KB; | |
private static final int THRESHOLD = 32 * KB; | |
private static final int[] TEST_SIZE = new int[]{ 16 * KB, 32 * KB, 128 * KB, 1 * MB, 32 * MB}; | |
public static void main(String[] args) throws IOException { | |
for (int writeSize : TEST_SIZE) { | |
testFileBackedOutputStream(writeSize); | |
testByteArrayOutputStream(writeSize); | |
System.out.println(); | |
} | |
} | |
private static void testFileBackedOutputStream(int writeSize) throws IOException { | |
test(new FileBackedOutputStream(THRESHOLD), writeSize); | |
} | |
private static void testByteArrayOutputStream(int writeSize) throws IOException { | |
test(new ByteArrayOutputStream(), writeSize); | |
} | |
private static void test(OutputStream oStream, int writeSize) throws IOException { | |
BufferedOutputStream buffer = new BufferedOutputStream(oStream); | |
byte[] bytes = new byte[KB]; | |
Stopwatch watch = new Stopwatch().start(); | |
try { | |
for (int i = 0; i < writeSize / KB; ++i) { | |
buffer.write(bytes); | |
} | |
watch.stop(); | |
} finally { | |
buffer.close(); | |
} | |
System.out.printf( | |
"I\'ve finished to write %,12d bytes in %,6d msec via %s%n", | |
writeSize, | |
watch.elapsedMillis(), | |
oStream.getClass().getName()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment