[英]I have a system.properties file present in WEB-INF/config folder. How to write a code for retrieving data from this file?
[英]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.