FrankSharp
FrankSharp

Reputation: 2632

Read a particuliar line in txt file in Java

The file ListeMot.txt contain 336529 Line

How to catch a particular line.

This my code

 int getNombre()
 {
   nbre = (int)(Math.random()*336529);
   return nbre ;
 }

public String FindWord () throws IOException{
   String word = null;
   int nbr= getNombre();
   InputStreamReader reader = null;
   LineNumberReader lnr = null;
   reader = new InputStreamReader(new FileInputStream("../image/ListeMot.txt"));
   lnr = new LineNumberReader(reader);
   word = lnr.readLine(nbr);
}

Why I can't get word = lnr.readLine(nbr);??

Thanks

P.S I am new in java!

Upvotes: 5

Views: 798

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533520

To get the Nth line you have to read all the lines before it.

If you do this more than once, the most efficient thing to do may be to load all the lines into memory first.


private final List<String> words = new ArrayList<String>();
private final Random random = new Random();

public String randomWord() throws IOException {
    if (words.isEmpty()) {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("../image/ListeMot.txt")));
        String line;
        while ((line = br.readLine()) != null)
            words.add(line);
        br.close();
    }
    return words.get(random.nextInt(words.size()));
}

BTW: The the parameter theWord meant to be used?

Upvotes: 3

josefx
josefx

Reputation: 15656

The LineNumberReader only keeps track of the number of lines read, it does not give random access to lines in the stream.

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

There is no method like readLine(int lineNumber) in Java API. You should read all previous lines from a specific line number. I have manipulated your 2nd method, take a look at it:

public void FindWord () throws IOException
{
    String word = "";
    int nbr = getNombre();
    InputStreamReader reader = null;
    LineNumberReader lnr = null;
    reader = new InputStreamReader( new FileInputStream( "src/a.txt" ) );
    lnr = new LineNumberReader( reader );

    while(lnr.getLineNumber() != nbr)
        word = lnr.readLine();

    System.out.println( word );
}

The above code is not error free since I assume you know the limit of the line number in the given text file, i.e. if we generate a random number which is greater than the actual line number, the code will go into an infinite loop, be careful.

Another issue, line numbers start from 1 so I suggest you to change your random line number generator method like this:

int getNombre()
 {
   nbre = (int)(Math.random()*336529) + 1;
   return nbre ;
 }

Upvotes: 1

Related Questions