![](/img/trans.png)
[英]Java: Using .txt files to assign specific indexes of each line to an arraylist
[英]Creating an app - Java - create an arraylist from a .txt file and toast specific line of arraylist
我想做的是創建一個包含1000個左右條目的字符串數組。 而不是做:
public void DefaultGeneric(View v) throws FileNotFoundException{
Random rand = new Random();
int i = rand.nextInt(4) + 0;
int j = rand.nextInt(4) + 0;
String[] SomeThingA = {"yep","okay","nope"}; //I need this array to be much much larger but want a better way of doing it.
String[] SomeThingB = {"test","test1","test2"}; //I need this array to be much much larger but want a better way of doing it.
Toast.makeText(getBaseContext(), SomeThingA[i]+SomeThingB[j], Toast.LENGTH_LONG ).show();
}
聲明我的長數組,我一直在研究如何使用所有數組值創建一個.txt
文件,然后使用arraylist。 但是每次嘗試都會失敗。 另外,一旦弄清楚如何使用arraylist,我就需要使用: Toast.makeText(getBaseContext(), variable, Toast.LENGTH_SHORT).show
調用我的arraylist的特定行。
任何幫助將不勝感激。 謝謝!
我建議您如下創建JSON文件
[
"entryOne",
"entryTwo",
"...",
"entryN"
]
現在將此文件存儲在資產中,並按如下所示加載它(感謝https://stackoverflow.com/a/13814551/7274758 )
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
}
catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
然后,您可以嘗試通過JSONArray創建此JSON字符串的數組
JSONArray arr = new JSONArray(loadJSONFromAsset());
要從行中檢索字符串,只需調用getString - arr.getString (rowNo)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.