測試環境 eben T4 android 2.3.4

小檔時RandomAccessFile 比FileOutputStream 快

大檔正好相反FileOutputStream 比 RandomAccessFile 快

我測試

100M , final int length = 1024 * 1024 * 100; 時間ms
RandomAccessFile write: 104857600耗 時:33874
BufferedOutputStream write: 104857600耗 時:17814

50M , final int length = 1024 * 1024 * 50; 時間ms
RandomAccessFile write:52428800 耗時:16430
BufferedOutputStream write:52428800 耗時:9497

10M , final int length = 1024 * 1024 * 10; 時間ms
RandomAccessFile write:10485760 耗時:454
BufferedOutputStream write:10485760 耗時:958


建議開發者存儲檔時選擇適合的方式。



測試代碼如下:

private void testFileWrite(){
RandomAccessFile mRandomAccessFile = null;
File randomFile;
randomFile = new File("/sdcard/randomFile.test");

final int length = 1024 * 1024 * 10; // *100 //*50
byte buffer[] = new byte[1024];
for (int i = 0; i < 1024; ++i) {
buffer[i] = (byte) (0xFF & i);
}

long start_time = System.currentTimeMillis();
try {
mRandomAccessFile = new RandomAccessFile(randomFile, "rw");
mRandomAccessFile.setLength(length);
for (int i = 0, max = length / 1024; i < max; ++i){
mRandomAccessFile.write(buffer, 0, 1024);
}
if (mRandomAccessFile != null) {
mRandomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
long end_time = System.currentTimeMillis();
Log.d("", "RandomAccessFile write:" + length +" 耗時:"+(end_time-start_time));
start_time = System.currentTimeMillis();
/////////////////////////////////////////////////////////////////////////
FileOutputStream downFileWriter = null;
BufferedOutputStream downFileBuffer = null;
File streamFile = new File("/sdcard/streamFile.test");

try {
downFileWriter = new FileOutputStream(streamFile, true);
downFileBuffer = new BufferedOutputStream(downFileWriter,102400);
for (int i = 0, max = length / 1024; i < max; ++i){
downFileBuffer.write(buffer, 0, 1024);
}

if (null != downFileBuffer) {
downFileBuffer.flush();
downFileBuffer.close();
downFileBuffer = null;
}
if (null != downFileWriter){
downFileWriter.flush();

downFileWriter.close();

downFileWriter = null;

}
} catch (Exception e) {

e.printStackTrace();
}

end_time = System.currentTimeMillis();
Log.d("", "BufferedOutputStream write:" + length +" 耗時:"+(end_time-start_time));
}
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()