读取大文件的方法这里有三种,
第一种,使用commons-io的FileUtils的类进行读取
第二种,使用Scanner进行读取
第三种,使用cache进行读取
读取文件大小:102M
使用commons-io的FileUtils类进行读取publicstaticvoidtestReadFile() {try{
LineIterator lineIterator= FileUtils.lineIterator(newFile("D:/test.log"), "UTF-8");while(lineIterator.hasNext()) {
String line=lineIterator.nextLine();
System.out.PRintln(line);
}
}catch(IOException e) {
e.printStackTrace();
}
}
读取时间在8秒左右
使用Scanner进行读取:publicstaticvoidtestScannerReadFile() {
FileInputStream fileInputStream=null;
Scanner scanner=null;try{
fileInputStream=newFileInputStream("D:/test.log");
scanner=newScanner(fileInputStream, "UTF-8");while(scanner.hasNext()) {
String line=scanner.nextLine();
System.out.println(line);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}finally{if(fileInputStream !=null) {try{
fileInputStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}if(scanner !=null) {
scanner.close();
}
}
}
读取时间在10秒左右
使用cache读取publicstaticvoidreadCache() {
String filename= "D:/test.log";
File file=newFile(filename);
BufferedReader reader=null;try{
reader=newBufferedReader(newFileReader(file), 10 * 1024 * 1024);//读大文件 设置缓存String tempString =null;while((tempString = reader.readLine()) !=null) {
System.out.println(tempString);
}
reader.close();
}catch(IOException e) {
e.printStackTrace();
}finally{if(reader !=null) {try{
reader.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
读取时间在8秒左右,与commons-io的FileUtils不相上下,我这边暂时没有更大的文件进行比较如果,有更大的文件,欢迎进行测试比较。