在Java中再次将2D数组转换为String和String转换为2D String

时间:2015-11-18 13:24:25

标签: java arrays string parsing

我有一个看起来像这样的数组:

String private String array[][];

array = [["smthng","smthng","smthng","smthng"],
["smthng","smthng","smthng","smthng"]];

我想将它转换为String来存储它,然后再将其转换为2D数组,但我总是得到indexoutboundexception。

我试过了:

private String twoDimensionalStringArrayToString(String[][] myArray) throws IOException {
    String res = "";
    for (int iRow = 0; iRow < myArray.length; iRow++) {
        for (int iCol = 0; iCol < myArray[iRow].length; iCol++)
            res += myArray[iRow][iCol] + ",";
        res += "\n";
    }
    return res;
}

private String[][] stringToTwoDimensionalStringArray(String res) throws ClassNotFoundException, IOException {

    String[] rows = res.split("\n");
    String[][] myArray = new String[rows.length][];
    for (int iRow = 0; iRow < rows.length-1; iRow++) {
        String[] cols = rows[iRow].split(",");
        myArray[iRow] = new String[cols.length];
        for (int iCol = 0; iCol < cols.length; iCol++)
            myArray[iRow][iCol] = cols[iCol];
    }
    return myArray;
}

然后我这样做来保存字符串:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("MAPA", twoDimensionalStringArrayToString(mapa));

这是为了阅读它:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mapa = stringToTwoDimensionalStringArray(sharedPref.getString("MAPA", null));

0 个答案:

没有答案