java读取大文本文件
原文:http://blog.csdn.net/k21325/article/details/53886160
小文件当然可以直接读取所有,然后放到内存中,但是当文件很大的时候,这个方法就行不通了,内存不是这么玩的~~
那么,下面是解决方法:
1.Java底层:调用java的java.util.Scanner类扫描文件内容,一行一行,连续读取
FileInputStream inputStream = null;Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
2.commons-io
LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
LineIterator.closeQuietly(it);
}
以上是 java读取大文本文件 的全部内容, 来源链接: utcz.com/z/394991.html