如何从文本文件中读取特定行? [英] How Can I Read A Specific Line From A Text File ?

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

问题描述

Lets say I have a file like this:

'Line 1'
"Line 2"
"Line 3"



如何从文件中读出特定行?


How would I read out a specific line from the file?

推荐答案

由于你现在没有第3行开始的地方,你不能跳到那里只读线,所以你必须浪费时间并阅读所有的线路才能到达所要求的线路...

这段代码可以完成这项工作,但考虑重新设计你的应用程序,因为当文件变大时代码效率会非常低......

As you do not now where the 3rd line begins you can not jump to there and read only the line, so you have to waste time and read all the lines before you get to the requested one...
This code will do the job, but consider to re-design your application as the code will be very inefficient when the file grows large...
BufferedReader oBuffer = new BufferedReader(new FileReader(szPath))) {
String szLine;
int nCount = 0;
while ((szLine = oBuffer.readLine()) != null) {
  nCount++;

  if(nCount > 3) break;
}


除非你的行总是完全相同 - 并且它们在你的例子中,但在现实世界中很少变化 - 你读取时不能跳过行,因为文本文件没有行:它有行终止字符,表示行何时结束。

这意味着你必须读取所有行进入内存并挑选你想要的内容: Files.readAllLines [< a href =http://www.java2s.com/Tutorials/Java/java.nio.file/Files/Java_Files_readAllLines_Path_path_Charset_cs_.htmtarget =_ blanktitle =New Window> ^ ]将有助于在那里,或逐行读取文件并丢弃你不想要的文件。
Unless your lines are always exactly the same length - and they are in your example, but vary rarely are in the real world - you can't "skip lines" when you read, because a text file doesn't have lines: it has line termination characters which indicate when lines end instead.
Which means that either you must read all lines into memory and pick the ones you want: Files.readAllLines[^] will help there, or read the file line-by line and discard the ones you don't want.


参考:从文本文件中读取特定行 [ ^ ]


这篇关于如何从文本文件中读取特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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