把数据放大到2亿条,21GB,io缓冲读取19s,nio读取20s,普通读取61s,本地文件的读取还是使用io缓冲比较合适,性能提高3倍
读取本地文件还是用io缓存读比较快,nio读取速度差不多,但nio的优势不在此,nio不会阻塞,新的编程方式和阻塞处理机制
磁盘吃满,300mb/s
cpu基本不变
内存基本不变
/**
* 文本读取和写入的性能测试
*/
public class txtPerformanceTest {
/**
* 固态环境
* 2亿次写入 15个字段 \t分割符 时间61478 大小21.4GB
* 普通读取 时间69375
* io缓存去读 时间19099
* nio读取 时间20672
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File file=new File("E:\\Desktop\\txt测试文件.txt");
//循环写入txt文件,
// int count=200000000;
// writeFile(file,count);
//读取txt文件
// readFile(file);
//缓冲io读取文件
// cacheReadFile(file);
//nio读取文件
// nioReadFile(file);
}
/**
* nio读写文件
* @param file
* @throws IOException
*/
public static void nioReadFile(File file)throws IOException{
FileInputStream fin=new FileInputStream(file);
// FileOutputStream fout=new FileOutputStream(file);
FileChannel fic= fin.getChannel();
// FileChannel foc=fout.getChannel();
ByteBuffer buf=ByteBuffer.allocate(10240);
long startTime=System.currentTimeMillis();
while(fic.read(buf)!=-1){
buf.flip();//切换到读取数据模式
// foc.write(buf);
buf.clear();//清空缓冲区
}
long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
fin.close();
// foc.close();
}
/**
* io缓存读取文件
* @param file
* @throws IOException
*/
public static void cacheReadFile(File file)throws IOException{
InputStream in=new BufferedInputStream(new FileInputStream(file));
// OutputStream out=new BufferedOutputStream(new FileOutputStream(file));
int len=0;
byte[] data= new byte[10240];
long startTime=System.currentTimeMillis();
while ((len=in.read(data))!=-1){
// out.write(data, 0, len);
}
long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
in.close();
// out.close();
}
/**
* 普通的文件读流
* @param file
* @throws IOException
*/
public static void readFile(File file)throws IOException{
InputStreamReader reader=new InputStreamReader(new FileInputStream(file));
BufferedReader br=new BufferedReader(reader);
String line="";
long startTime=System.currentTimeMillis();
line = br.readLine();
while (line != null) {
line = br.readLine(); // 一次读入一行数据
}
long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
}
/**
* 文件写流
* @param file
* @param count
* @throws IOException
*/
public static void writeFile(File file,int count) throws IOException{
BufferedWriter out = null;
file.createNewFile();
out= new BufferedWriter (new FileWriter(file));
int i=0;
long startTime=System.currentTimeMillis();
while(i<count){
out.write("你猜我是谁\txxxx\tAAAAAAA\tTTTTTTTT\txxxx\txxxx\txxxx\txxxx\tASDAQDWQQDWQQxxxx\txxQxx\txxxQx\txQxxx\txxqqqxx\txsaxx\txxaxx\t\n");
i++;
}
out.flush(); // 把缓存区内容压入文件
out.close(); // 最后记得关闭文件
long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
}
}
image.png