shihaiming

原文: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);
}

 

分类:

技术点:

相关文章:

  • 2021-09-07
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
  • 2021-12-17
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
猜你喜欢
  • 2021-09-07
  • 2021-09-07
  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
相关资源
相似解决方案