讀取大文件的方法這里有三種,
第一種,使用commons-io的FileUtils的類進行讀取
第二種,使用Scanner進行讀取
第三種,使用cache進行讀取
讀取文件大小:102M
使用commons-io的FileUtils類進行讀取
public static void testReadFile() { try { LineIterator lineIterator = FileUtils.lineIterator(new File("D:/test.log"), "UTF-8"); while (lineIterator.hasNext()) { String line = lineIterator.nextLine(); System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
讀取時間在8秒左右
使用Scanner進行讀取:
public static void testScannerReadFile() { FileInputStream fileInputStream = null; Scanner scanner = null; try { fileInputStream = new FileInputStream("D:/test.log"); scanner = new Scanner(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讀取
public static void readCache() { String filename = "D:/test.log"; File file = new File(filename); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(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不相上下,我這邊暫時沒有更大的文件進行比較如果,有更大的文件,歡迎進行測試比較。