How to get a random line from text file in Android using Android Studio 2.1.3?

纵然是瞬间 提交于 2019-12-10 23:38:48

问题


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:


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.



来源:https://stackoverflow.com/questions/39033090/how-to-get-a-random-line-from-text-file-in-android-using-android-studio-2-1-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!