Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reading nth line

Tags:

java

file-io

I am trying to read a specific line from a text file, however I don't want to load the file into memory (it can get really big).

I have been looking but every example i have found requires either to read every line (this would slow my code down as there are over 100,000 lines) or load the whole thing into an array and get the correct element (file will have alot of lines to input).

An example of what I want to do:

String line = File.getLine(5);

"code is not actual code, it is made up to show the principle of what i want"

Is there a way to do this?

-----Edit-----

I have just realized this file will be written too in between reading lines (adding to the end of the file).

like image 687
NoLiver92 Avatar asked Apr 24 '13 19:04

NoLiver92


People also ask

How do you read a certain number of lines in Java?

Java supports several file-reading features. One such utility is reading a specific line in a file. We can do this by simply providing the desired line number; the stream will read the text at that location. The Files class can be used to read the n t h nth nth line of a file.

How do you read the second line of a text file in Java?

//read the file, line by line from txt File file = new File("train/traindata. txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; line = br. readLine(); while(line != null) { lines = line.

How do you read a new line in Java?

To read data and move on to the next line, we should use the nextLine() method. This method moves the scanner past the current line and returns the rest of the current line, excluding any line separator at the end. The read position is then set to the beginning of the next line.

How do you read a single line in Java?

Using the Java BufferedRedaer class is the most common and simple way to read a file line by line in Java. It belongs to java.io package. Java BufferedReader class provides readLine() method to read a file line by line.


1 Answers

Is there a way to do this?

Not unless the lines are of a fixed number of bytes each, no.

You don't have to actually keep each line in memory - but you've got to read through the whole file to get to the line you want, as otherwise you won't know where to start reading.

like image 50
Jon Skeet Avatar answered Sep 21 '22 03:09

Jon Skeet