您的位置:首页 > 编程语言 > Java开发

疑问:调用Java NIO提高文件读写速度

2011-11-18 10:26 435 查看
在51cto上看到一篇文章
调用Java NIO提高文件读写速度http://developer.51cto.com/art/201111/302489.htm

说调用Java NIO提高文件读写速度

因此很好奇,然后自己写了测试类,代码如下:

import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class ReadFileTest {

/**
* @param args
*/
public static void main(String[] args) {
String filePath = "F:\\23Test\\wls1034_oepe111161_linux32.bin";
Long sTime;
Long eTime;
ReadFileTest r = new ReadFileTest();

// item1
sTime = System.currentTimeMillis();
r.readFileIO(filePath);
eTime = System.currentTimeMillis();
System.out.println("IO耗时:" + (eTime - sTime));

// item2
sTime = System.currentTimeMillis();
r.readFileNIO(filePath);
eTime = System.currentTimeMillis();
System.out.println("NIO耗时:" + (eTime - sTime));

}

private void readFileIO(String filePath) {
String outFile = "F:\\23Test\\io-bak.bin";
File inFile = new File(filePath);
int bytesum = 0;
int byteread = 0;
if (inFile.exists()) {
FileInputStream inStream;
FileOutputStream fs;
try {
inStream = new FileInputStream(inFile);
fs = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
} catch (Exception e) {
e.printStackTrace();
}

}

}

private void readFileNIO(String filePath) {
String outFile = "F:\\23Test\\nio-bak.bin";
File inFile = new File(filePath);
try {
FileInputStream inf = new FileInputStream(inFile);
FileOutputStream outf = new FileOutputStream(outFile);
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 准备文件读取的管道-->相当于烟仓和烟管
FileChannel inFc = inf.getChannel();
FileChannel outFc = outf.getChannel();
//Charset charSet = Charset.forName("utf-8");
// 进行编码解码-->相当于水斗中水的过滤作用
//CharsetDecoder decoder = charSet.newDecoder();
//CharsetEncoder encoder = charSet.newEncoder();
while (true) {
// 准备向Buffer中写入数据-->相当于点燃烟丝,完事具备只欠东风
buffer.clear();
// 进行字符编码 -->相当于水的过滤作用
//CharBuffer cb = decoder.decode(buffer);
//ByteBuffer bb = encoder.encode(cb);

// 数据经过编码以后暂存缓冲区-->相当于经过水过滤后的烟暂停在水斗中
int t = inFc.read(buffer);
if (t == -1) {
break;
}
buffer.flip();
//bb.flip();
// 将字节码写入目标文件-->相当于烟已经进入到嘴里
outFc.write(buffer);
}
inFc.close();
outFc.close();
inf.close();
outf.close();
} catch (Exception e) {
e.printStackTrace();
}

}

}
结果如下 :

第一轮测试

IO耗时:36597

NIO耗时:46376

第二轮测试

IO耗时:35492

NIO耗时:43809

第三轮测试

IO耗时:49827

NIO耗时:50920

经过几轮测试下来,我发现用NIO通道的,效率没有以前代码的写法效率高,第次都比较慢

所以我认为用他说的这种方式并没有提高访问文件的速度

请有知道的高人能够给我解惑?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: