简体   繁体   中英

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

PS I am new in java!

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?

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, ie 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 ;
 }

LineNumberReader仅跟踪读取的行数,而不提供对流中行的随机访问。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM