主要對普通io的讀寫效率進行對比。dom
代碼以下:測試
public class IOTest {input
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
outputStreamTest();
// bufferedOutputStreamTest();
randomAccessFileWriteTest();
// inputStreamTest();
// bufferedInputStreamTest();
// randomAccessFileReadTest();
}it
private static void outputStreamTest() throws Exception {
FileOutputStream out = new FileOutputStream(new File("data"));
byte[] value = new byte[1024];
int lop = 1024 * 1024;
long start = System.currentTimeMillis();
for (int i = 0; i < lop; i++) {
out.write(value);
}io
long end = System.currentTimeMillis();
System.out.println(end - start);
out.close();class
}效率
private static void bufferedOutputStreamTest() throws Exception {
FileOutputStream out = new FileOutputStream(new File("data"));
BufferedOutputStream bOut = new BufferedOutputStream(out);
byte[] value = new byte[1024];
int lop = 1024 * 1024;
long start = System.currentTimeMillis();
for (int i = 0; i < lop; i++) {
bOut.write(value);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
bOut.close();im
}static
private static void randomAccessFileWriteTest() throws Exception {
RandomAccessFile raf = new RandomAccessFile(new File("data"), "rw");
byte[] value = new byte[1024];
int lop = 1024 * 1024;
long start = System.currentTimeMillis();
for (int i = 0; i < lop; i++) {
raf.write(value);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
raf.close();
}while
private static void inputStreamTest() throws Exception {
FileInputStream in = new FileInputStream(new File("data"));
byte[] buf = new byte[1024];
int readCount = -1;
long totalCount = 0;
long start = System.currentTimeMillis();
while ((readCount = in.read(buf)) != -1) {
totalCount += readCount;
}
long end = System.currentTimeMillis();
System.out.println("讀取:" + totalCount + "個字節,耗時:" + (end - start));
in.close();
}
private static void bufferedInputStreamTest() throws Exception {
FileInputStream in = new FileInputStream(new File("data"));
BufferedInputStream bin = new BufferedInputStream(in);
byte[] buf = new byte[1024];
int readCount = -1;
long totalCount = 0;
long start = System.currentTimeMillis();
while ((readCount = bin.read(buf)) != -1) {
totalCount += readCount;
}
long end = System.currentTimeMillis();
System.out.println("讀取:" + totalCount + "個字節,耗時:" + (end - start));
bin.close();
}
private static void randomAccessFileReadTest() throws Exception {
RandomAccessFile raf = new RandomAccessFile(new File("data"), "r");
byte[] buf = new byte[1024];
int readCount = -1;
long totalCount = 0;
long start = System.currentTimeMillis();
while ((readCount = raf.read(buf)) != -1) {
totalCount += readCount;
}
long end = System.currentTimeMillis();
System.out.println("讀取:" + totalCount + "個字節,耗時:" + (end - start));
raf.close();
}
}
測試結果以下:
寫效率:BufferedOutputStream > FileOutputStream > RandomAccessFile
讀效率:BufferedInputStream > FileInputStream 約等於 RandomAccessFile