How to Read a Specific Line Using the Specific Line Number from a 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();

Read specific portion of a file by counting line number in java platform

Don't call setLineNumber(). It just changes the value returned by getLineNumber(), it doesn't skip anything in the input stream. The documentation, i.e. the javadoc of LineNumberReader, says so explicitly:

Note however, that setLineNumber(int) does not actually change the current position in the stream; it only changes the value that will be returned by getLineNumber().

To only process some of the lines from the file, simply add an if statement:

public static void main(String[] args) throws Exception {
File file = new File("H://java//newFile.txt");
try (LineNumberReader reader = new LineNumberReader(new FileReader(file))) {
for (String line; (line = reader.readLine()) != null; ) {
if (reader.getLineNumber() >= 50 && reader.getLineNumber() <= 150) {
System.out.println(reader.getLineNumber() + ": " + line);
}
}
}
}

Of course, with an upper limit on line number, there is no reason to keep reading after that, so you should do it like this:

File file = new File("H://java//newFile.txt");
try (LineNumberReader reader = new LineNumberReader(new FileReader(file))) {
for (String line; (line = reader.readLine()) != null; ) {
if (reader.getLineNumber() > 150)
break;
if (reader.getLineNumber() >= 50) {
System.out.println(reader.getLineNumber() + ": " + line);
}
}
}

If you don't need to know the line number, then with Java 8+ Streams, it's even easier:

Path file = Paths.get("H://java//newFile.txt");
Files.lines(file).limit(150).skip(49).forEach(System.out::println);

Read a specific line from file and separate the data from one line

Hope this will help

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FindGivenStringFromFile {

public static void main(String args[]) throws FileNotFoundException {

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter a filename >> ");
String filename = keyboard.nextLine();

File f = new File(filename);
Scanner fin = new Scanner(f);

System.out.println("Enter item ID: ");
int fruitID = keyboard.nextInt();

//Reading each line of file using Scanner class
int lineNumber = 1;
while (fin.hasNextLine()) {
String line = fin.nextLine();
String[] lineDataArray = line.split("\\^");
if(lineDataArray != null && lineDataArray.length >2){
if(Integer.parseInt(lineDataArray[1]) == fruitID){
System.out.println("Item: " + lineDataArray[0]);
System.out.println("Id: " + lineDataArray[1]);
System.out.println("price: $" + lineDataArray[2]);
}

lineNumber++;
}

}
}
}

Java how to get specific line and its number

Your program contains multiple bugs.

new Scanner("test.txt")

First of the the above call doesn't scan a file, rather it scans the string that you provide.

 scan.nextLine();
if(scan.nextLine().startsWith("12345"))
{
break;
}

Here you call nextLine() twice. You better call it once and assign its result to a variable.

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 )

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 do I read from a certain line until a certain line?

(Posted solution on behalf of the OP).

I just need to remove the first while loop.

String line;
int currentLineNo = 1;
int startLine = 20056;//40930;
int endLine = 1159450;

FileReader file = new FileReader("yourfilepath");
BufferedReader reader = new BufferedReader(file);

PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");

while(currentLineNo<=endLine)
{
line = reader.readLine();
if(currentLineNo >= startLine && currentLineNo<=endLine)
{ System.out.println(line); }

currentLineNo++;
}

reader.close();
writer.close();

Credit to Jay Hamilton.



Related Topics



Leave a reply



Submit