InputStreamReader并从.txt文件中读取随机行 [英] InputStreamReader and reading random lines from .txt file

查看:176
本文介绍了InputStreamReader并从.txt文件中读取随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有一种方法可以从文本文件中读取随机行并将其返回。我使用randTxt()来读取并返回txt文件中的随机行。
,但它每次只显示相同的行(第1行)。

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?

推荐答案

这是使用BufferedReader执行所需操作的框架。在这种情况下,您不需要将值存储在临时数组中。

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);

这篇关于InputStreamReader并从.txt文件中读取随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆