Read a particular line in a txt file in Java

ListeMot.txt file contains line 336529

How to catch a specific string.

This is 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 can't I get the word = lnr.readLine (nbr); ??

thank

PS I am new to java!

+5
source share
3 answers

To get the Nth line, you must read all the lines before it.

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


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: Used parameter theWord?

+3
source

There is no method in the Java API, for example readLine(int lineNumber). You must read all previous lines from a specific line number. I manipulated your second 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 );
}

, , , .. , , , , .

: 1, :

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

LineNumberReader monitors only the number of lines read, does not give random access to lines in the stream.

+1
source

All Articles