How to get a random line from text file in Android

2019-07-17 12:59发布

I have a text file with 500 lines. I placed this text file in app/src/main/assets folder with the name "words.txt". In this file each line is separated with line break. Now i need to get random line from this text file. I visited following questions prior to posting this.

How to load random line from text file in android?

InputStreamReader and reading random lines from .txt file

How to grab a random line from a text file and print the line [duplicate]

How to get a random line of a text file in Java?

Reading a random line from text file in android

I have constructed my code from above links as well as this one. I did not know that some class called line number reader exists.

Here is my code:

try {
        //Initialize assetmanager class
        AssetManager am = this.getAssets();
        //open file using asset manager
        InputStream is = am.open("words.txt");
        //read buffer manager
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        //Important: use of LineNumberReader Class
        LineNumberReader lnr = new LineNumberReader(reader);
        Random r = new Random();
        int n = r.nextInt(500)+1;
        lnr.setLineNumber(n);
        mWord = lnr.readLine();
        Log.d("MyLog","The letter is "+mWord);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Now this code works but always gives the first line. The random number is generated but the lnr (LineNumberReader) reads first line always. Why?

This is for learning purpose. For current case i know the length of file (or total no of lines) are 500.

1条回答
Viruses.
2楼-- · 2019-07-17 13:25

Now this code works but always gives the first line. The random number is generated but the lnr (LineNumberReader) reads first line always. Why?

See this LineNumberReader

Note however, that setLineNumber(int) does not actually change the current position in the stream; it only changes the value that will be returned by getLineNumber().

So that's why it reading first line always.

查看更多
登录 后发表回答