Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a particular line from a text file in Java

What is the most efficient way to extract specific line numbers of data from a text file? For example, if I use the Scanner to parse a file, do I first have to create an array with a length matching the total number of lines in the text file?

If a text file has 30 lines and I only want to work with lines 3, 8, and 12, is there a way to specifically only read those lines?

like image 254
Jon Avatar asked Jul 25 '13 07:07

Jon


People also ask

How do you read a paragraph line by line in Java?

We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java. util.

How do I read a delimited text file in Java?

You can use BufferedReader to read large files line by line. If you want to read a file that has its content separated by a delimiter, use the Scanner class. Also you can use Java NIO Files class to read both small and large files.

How do I read a file line by line?

Java Read File line by line using BufferedReader We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.


1 Answers

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();            
        }
    }
}
}
like image 143
No Idea For Name Avatar answered Sep 22 '22 15:09

No Idea For Name