在51cto上看到一篇文章 调用Java NIO提高文件读写速度http://developer./art/201111/
说调用Java NIO提高文件读写速度
因此很好奇,然后自己写了测试类,代码如下:
import .*;
import .*;
import ;
import ;
import ;
import ;
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 = ();
(filePath);
eTime = ();
("IO耗时:" + (eTime - sTime));
// item2
sTime = ();
(filePath);
eTime = ();
("NIO耗时:" + (eTime - sTime));
}
private void readFileIO(String filePath) {
String outFile = "F:\\23Test\\";
File inFile = new File(filePath);
int bytesum = 0;
int byteread = 0;
if (()) {
FileInputStream inStream;
FileOutputStream fs;
try {
inStream = new FileInputStream(inFile);
fs = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
while ((byteread = (buffer)) != -1) {
bytesum += byteread;
(buffer, 0, byteread);
}
();
();
} catch (Exception e) {
();
}
}
}
private void readFileNIO(String filePath) {
String outFile = "F:\\23Test\\";
File inFile = new File(filePath);
try {
FileInputStream inf = new FileInputStream(inFile);
FileOutputStream outf = new FileOutputStream(outFile);
ByteBuffer buffer = (1024);
// 准备文件读取的管道-->相当于烟仓和烟管
FileChannel inFc = ();
FileChannel outFc = ();
//Charset charSet = ("utf-8");
// 进行编码解码-->相当于水斗中水的过滤作用
//CharsetDecoder decoder = ();
//CharsetEncoder encoder = ();
while (true) {
// 准备向Buffer中写入数据-->相当于点燃烟丝,完事具备只欠东风
();
// 进行字符编码 -->相当于水的过滤作用
//CharBuffer cb = (buffer);
//ByteBuffer bb = (cb);
// 数据经过编码以后暂存缓冲区-->相当于经过水过滤后的烟暂停在水斗中
int t = (buffer);
if (t == -1) {
break;
}
();
//();
// 将字节码写入目标文件-->相当于烟已经进入到嘴里
(buffer);
}
();
();
();
();
} catch (Exception e) {
();
}
}
}
结果如下 :
第一轮测试
IO耗时:36597
NIO耗时:46376
第二轮测试
IO耗时:35492
NIO耗时:43809
第三轮测试
IO耗时:49827
NIO耗时:50920
经过几轮测试下来,我发现用NIO通道的,效率没有以前代码的写法效率高,第次都比较慢
所以我认为用他说的这种方式并没有提高访问文件的速度
请有知道的高人能够给我解惑?