繁体   English   中英

我在资产文件夹中有一个文本文件。 如何从该文本文件访问随机句子?

[英]I have a text file in the assets folder. How can I access a random sentence from that text file?

我在资产文件夹中创建了灵感文本文件。 在该灵感文件中,大约有20个句子。 因此,我如何随机选择一个句子并在文本视图中显示。 现在,它显示所有20个句子。 这是代码。 任何人都可以在这里帮助我。

tv_text1 = (TextView) findViewById(R.id.textView3);
String text = "";
try {
    InputStream is = getAssets().open("inspiration.txt");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();
    text = new String(buffer);
} catch (IOException ex) {
    ex.printStackTrace();
}
tv_text1.setText(text);

要从输入流中读取文本,请执行以下操作:

InputStream is = getAssets().open("inspiration.txt");    
List<String> doc =
          new BufferedReader(new InputStreamReader(resource,
              StandardCharsets.UTF_8)).lines().collect(Collectors.toList());

获取随机字符串:

String randomSentence = doc.get((new Random()).nextInt(items.size()));

尝试这样:

BufferedReader reader = null;
try {
  reader = new BufferedReader(
     new InputStreamReader(getAssets().open("inspiration.txt")));

  // do reading, usually loop until end of file reading
     String mLine;
     List<String> listLines  = new ArrayList<>();
     while ((mLine = reader.readLine()) != null) {
           //process line
           listLines.add(mLine);
     }

     if (listLines.size() > 0) {
         Random rand = new Random();
         int randomNumber = rand.nextInt(listLines.size());
         String randomLine = listLines.get(randomNumber);
         .......
     }

 } catch (IOException e) {
  //log the exception
 } finally {
   if (reader != null) {
      try {
         reader.close();
      } catch (IOException e) {
         //log the exception
    }
  }
}

如果句子之间用\\ n分隔,则可以这样做。 未经测试,您必须用为您提供这两个参数之间的随机数的东西替换randomGenerator。 在.split之后,您有一个数组,其中包含您加载的文本的所有行。

String splits[]=text.split('\n');
int random=randomGenerator(0,splits.length);
tv_text1.setText(splits[random]);

实际上,它比Android问题更像是一个通用的Java问题。 这是作业吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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