对于大文件的读取,如果我们使用普通的IO读取,肯定会引起内存的溢出,即便不会,也会占用极大的内存空间。下面提供了两种读取大文件的方式
1.使用java.util.Scanner进行对大文件的读取
public class ScannerTest {
public static void main(String[] args) {
new ScannerTest().read();
}
public void read() {
FileInputStream inputStream = null;
Scanner scanner = null;
try {
inputStream = new FileInputStream("D:/test.txt");
scanner = new Scanner(inputStream, "utf-8");
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
System.out.println(string);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
优点是:遍历文件的所有行,允许对每一行进行处理,而且不保持对他的引用。总之没有把他们放入内存,可以防止内存溢出。
2.使用apache的commons IO库实现
public class ApacheTest {
public static void main(String[] args) {
File file = new File("D:/test.txt");
LineIterator iterator = null;
try {
iterator = FileUtils.lineIterator(file, "utf-8");
while (iterator.hasNext()) {
String string = iterator.nextLine();
System.out.println(string);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (iterator != null) {
iterator.close();
}
}
}
}
两种方式都可以放置内存的溢出。当然还可以利用NIO对文件进行读取,这种方式我暂时还没有研究,后续会添加进来。