有没有一种实用的方法可以从文件中读取前n行? [英] Is there a utility method for reading first n lines from file?

查看:63
本文介绍了有没有一种实用的方法可以从文件中读取前n行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了以下热门图书馆:

I have searched the following popular libraries:

  • 番石榴- Fiels.readLines
  • nio - Files.readFirstLine Files.readAllLines
  • ApacheCommons - FileUtils.readLines
  • Guava - Fiels.readLines
  • nio - Files.readFirstLine or Files.readAllLines
  • ApacheCommons - FileUtils.readLines

所有方法都将整个文件作为String集合读取到内存中.但这对具有数千行的大型文件没有用吗?是否有一个简单的方法调用来读取其中任何一个库中文件的前 n 行?

All methods read whole file into memory as String collection. But that is not useful for large files with thousands of lines? Is there a simple method call to read the first n lines of a file in any of these libraries?

推荐答案

您可以使用

You could use LineNumberReader

LineNumberReader reader = 
    new LineNumberReader
      (new InputStreamReader(new FileInputStream("/path/to/file"), "UTF-8"));

try{
  String line;
  while (((line = reader.readLine()) != null) && reader.getLineNumber() <= 10) {
     ...
   }
}finally{
   reader.close()
}

这篇关于有没有一种实用的方法可以从文件中读取前n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆