总结一下应该只用jdk直接实现的话应该有3中方法:
1 使用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();
}
}
}
2 使用BufferedReader类设置一定的缓存,依然每次读取一行。
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();
}
}
}
}