在java中读取起始索引和结束索引之间的行

发布于 2024-08-27 08:05:12 字数 180 浏览 7 评论 0原文

假设我的文件中有 10 行。我有两个参数指定索引的开始和结束。

StartIndex = 2 // 指定前 2 行

最后 3 行

EndIndex = 3 // 指定我需要读取其间行的 。我知道维护索引和跳过是方法之一......但是还有其他有效的方法(即使使用外部库)吗?

谢谢

Lets say I have 10 lines in a file. I have 2 parameters that specify the beginning and ending of a index.

StartIndex = 2 // specifies the first 2 lines

EndIndex = 3 // specifies the last 3 lines

I need to read the lines in between. I know maintaining index and skipping is one of the ways...but are there any other efficient ways (even with external libraries)?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

满天都是小星星 2024-09-03 08:05:12

使用commons IO你可以轻松做到这一点,但效率不高,因为它将把整个文件加载到内存中。

File file = new File("myfile.txt");
List lines = FileUtils.readLines(file).subList(2,3);

http://commons.apache.org/io/

Using the commons IO you can do it easily, but it is not efficient because it will load the whole file in memory.

File file = new File("myfile.txt");
List lines = FileUtils.readLines(file).subList(2,3);

http://commons.apache.org/io/

雨后彩虹 2024-09-03 08:05:12

我想您是在问是否可以直接跳到文件的第三行而不读取前两行。一般来说(除非你有索引,正如你提到的)答案是否定的。您必须阅读前两行才能知道它们有多长,因此逐行读取文件并忽略第一行的简单解决方案大约是您能得到的最好的解决方案。

关于结束,如果您的结束索引是从文件开头开始的索引,那么您可以提前停止。但你的意思是文件末尾的第三行吗?在这种情况下,您还必须一直阅读到文件末尾才能知道何时停止。

一种特殊情况是,如果您知道所有线的长度相同。然后您可以直接查找文件中的正确位置并从那里开始阅读。

I guess you're asking if there is anyway to jump directly to the third line of the file without reading the first two lines. In general (unless you have an index, as you mentioned) the answer is no. You have to read the first two lines to know how long they are, so the simple solution of reading the file line-by-line and ignoring the first lines is about as good as you can get.

Regarding the end, if your end index is an index from the beginning of the file then you can stop early. But did you mean the 3rd line from the end of the file? In this case you will also have to read all the way to the end of the file to know when to stop.

One special case is if you know that all the lines are the same length. Then you can seek directly to the correct location in the file and start reading from there.

红ご颜醉 2024-09-03 08:05:12

正如其他人指出的那样,除非您了解有关文件内容的更多信息,否则您必须按顺序阅读才能找出行的开始位置。您可以使用 LineNumberReader 这是一个跟踪行号的缓冲字符输入流。

As the other guys pointed out, unless you know more information about the content of the file then no and you really have to read sequentially to find out where the lines begins. You can make use of LineNumberReader which is a buffered character-input stream that keeps track of line numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文