Search code examples
javaandroidinputstreamreader

InputStreamReader and reading random lines from .txt file


I have a method for my app to read a random line from a text file and return it. Im using the randTxt() to read and return a random line from the txt file. but it only shows the same line (1st line) everytime.

public String randTxt(){

  // Read in the file into a list of strings
  InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.randomstuff));
  //ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  String theLine="";
  int i;
  try {
    i = inputStream.read();
    while (i != -1) {
      i = inputStream.read();
    }
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  LineNumberReader  rdr = new LineNumberReader(inputStream);
  int numLines = 30;
  Random r = new Random();
  rdr.setLineNumber(r.nextInt(numLines));

  try {
    theLine = rdr.readLine();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  return theLine;
}

How can I fix it? and Can someone explain what's wrong in my code?


Solution

  • Here's the framework for doing what you need using BufferedReader. In this case, you don't need to store the values in a temp array.

    InputStreamReader inputStream = new InputStreamReader
      (getResources().openRawResource(R.raw.randomstuff));
    BufferedReader br = new BufferedReader(inputStream);
    int numLines = 30;
    Random r = new Random();
    int desiredLine = r.nextInt(numLines);
    
    String theLine="";
    int lineCtr = 0;
    while ((theLine = br.readLine()) != null)   {
      if (lineCtr == desiredLine) {
        break;
      }
      lineCtr++;
     }
    ...
    Log.d(TAG, "Magic line is: " +theLine);