Reading a Specific Line from a Text File in Java

How to read a specific line using the specific line number from a file in Java?

Unless you have previous knowledge about the lines in the file, there's no way to directly access the 32nd line without reading the 31 previous lines.

That's true for all languages and all modern file systems.

So effectively you'll simply read lines until you've found the 32nd one.

Reading a particular line from a text file in Java

here is how you do it:

import java.io.*;

public class Test {
public static void main(String [] args) {

// The name of the file to open.
String fileName = "temp.txt";
int counter = 0;

// This will reference one line at a time
String line = null;
FileReader fileReader = null;

try {
// FileReader reads text files in the default encoding.
fileReader =
new FileReader(fileName);

// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 3 || counter == 8 || counter == 12)
{
// do your code
}
}

}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
bufferedReader.close();
}
}
}
}

How can I get a specific line from a text file?

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

Reading specific lines of a text file in Java

This in my opinion is a bit cleaner than just skipping lines and it allows you to have access to the skipped elements incase you need them later :)

do
{
String[] entry = new String[3];

for (int i = 0; i < 3; i++)
{
if (opnEsoda.hasNextLine())
{
// Trim removes leading or trailing whitespace.
entry[i] = opnEsoda.nextLine().trim();
}
}

System.out.println(entry[2]);
}
while (opnEsoda.hasNextLine)

Reading a specific line from a text file in Java

String line = FileUtils.readLines(file).get(lineNumber);

would do, but it still has the efficiency problem.

Alternatively, you can use:

 LineIterator it = IOUtils.lineIterator(
new BufferedReader(new FileReader("file.txt")));
for (int lineNumber = 0; it.hasNext(); lineNumber++) {
String line = (String) it.next();
if (lineNumber == expectedLineNumber) {
return line;
}
}

This will be slightly more efficient due to the buffer.

Take a look at Scanner.skip(..) and attempt skipping whole lines (with regex). I can't tell if it will be more efficient - benchmark it.

P.S. with efficiency I mean memory efficiency

how can i read specific lines from a textfile in java 8?

You can use Files.lines which returns a Stream<String> with all lines and apply skip and limit to the result stream:

Stream<String> stream = Files.lines(Paths.get(fileName))
.skip(fromLine)
.limit(toLine - fromLine);

This will give you a Stream of lines starting from fromLine and ending at toLine. After that you can either convert it to a data structure (a list for example) or do whatever needs to be done.

How to read a file from a specific line to another specific line?

I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.

public static void main(String[] args) {
System.out.println("Escriba el ID Del Cliente");
String line2;
File file = new File(yourpathhere);
int lineCount = 0;
try {
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((line2 = readers.readLine()) != null) {
lineCount++;
if (line2.contains(CL.getId())) {
while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
System.out.println(line2);
line2 = readers.readLine();
}
output.close();
readers.close();
break;
}
}

} catch (IOException ex) {
System.out.println("ERRORR!!!!!!");
}
}

PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )



Related Topics



Leave a reply



Submit