繁体   English   中英

创建一个应用程序-Java-从.txt文件创建一个arraylist,并为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.

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