How can I get a specific line from a text file? [duplicate]

一世执手 提交于 2020-01-03 19:03:55

问题


I don't know how to get a specific line of text from a file. Let's say the text file is:

(1) john
(2) mark
(3) Luke

How can I get the second line of the text file (mark)? I just need to read it, not to edit it.


回答1:


int n = 2;
String lineN = Files.lines(Paths.get("yourFile.txt"))
                    .skip(n)
                    .findFirst()
                    .get();

For pre-Java 8, you could do for instance

int n = 2;
Scanner s = new Scanner(new File("test.txt"));
for (int i = 0; i < n-1; i++) // Discard n-1 lines
    s.nextLine();
String lineN = s.nextLine();



回答2:


There's no way to read a specific line without reading previous lines first. You could loop x number of times until you reach the line you desire.

For example:

FileReader fr = new FileReader("myfile.txt");
BufferedReader br = new BufferedReader(fr);
int lineNum = 2; //line of file to read
for(int i = 1; i < lineNum; i++)
     br.readLine();
System.out.println(br.readLine());



回答3:


You can use the Apache FileUtils class

File file = new File("file_name.txt");
String encoding = null; // default to platform
List<String> lines = FileUtils.readLines(file, encoding);
String line2 = lines.get(1);


来源:https://stackoverflow.com/questions/29637370/how-can-i-get-a-specific-line-from-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!