Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a particuliar line in txt file in Java

Tags:

java

io

file-io

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!

like image 231
FrankSharp Avatar asked Mar 17 '12 17:03

FrankSharp


2 Answers

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?

like image 147
Peter Lawrey Avatar answered Oct 12 '22 08:10

Peter Lawrey


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 ;
 }
like image 36
Juvanis Avatar answered Oct 12 '22 08:10

Juvanis