[英]I have a text file in the assets folder. How can I access a random sentence from that text file?
I have created inspiration text file in the assets folder. 我在资产文件夹中创建了灵感文本文件。 In that inspiration file, there are around 20 sentences. 在该灵感文件中,大约有20个句子。 So how do I pick any one sentence randomly and display in text view. 因此,我如何随机选择一个句子并在文本视图中显示。 Now it is displaying all 20 sentences. 现在,它显示所有20个句子。 Here is the code. 这是代码。 Can any one please help me here. 任何人都可以在这里帮助我。
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);
To read text from input stream: 要从输入流中读取文本,请执行以下操作:
InputStream is = getAssets().open("inspiration.txt");
List<String> doc =
new BufferedReader(new InputStreamReader(resource,
StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
Get Random String: 获取随机字符串:
String randomSentence = doc.get((new Random()).nextInt(items.size()));
Try like this: 尝试这样:
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
}
}
}
you could do it like this, if the sentences are separated by a \\n. 如果句子之间用\\ n分隔,则可以这样做。 untested, you have to replace randomGenerator with something that gives you a random number between those two parameters. 未经测试,您必须用为您提供这两个参数之间的随机数的东西替换randomGenerator。 after the .split you have an array with all the lines of the text you loaded. 在.split之后,您有一个数组,其中包含您加载的文本的所有行。
String splits[]=text.split('\n');
int random=randomGenerator(0,splits.length);
tv_text1.setText(splits[random]);
it's really more of a generic java question than an android question. 实际上,它比Android问题更像是一个通用的Java问题。 is this an assignment? 这是作业吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.