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.
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.
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();
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());
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);