gpt4 book ai didi

java - 我的 Assets 文件夹中有一个文本文件。如何从该文本文件中访问随机句子?

转载 作者:行者123 更新时间:2023-12-01 17:51:34 27 4
gpt4 key购买 nike

我在 Assets 文件夹中创建了灵感文本文件。在那个灵感文件中,大约有 20 个句子。那么我如何随机选择任何一个句子并显示在 TextView 中。现在它正在显示所有 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()));

关于java - 我的 Assets 文件夹中有一个文本文件。如何从该文本文件中访问随机句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49570860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com