在Java中将2D数组转换为字符串并再返回?

时间:2013-06-22 02:55:36

标签: java android arrays sqlite multidimensional-array

我需要在Android上的sqlite数据库中存储2d枚举数组,因此最简单的方法似乎是转换为字符串(例如CSV字符串)以存储在数据库中,然后在检索时再返回。

我怎样才能在java中做到这一点?

MyEnum[][] myArray;

由于

1 个答案:

答案 0 :(得分:2)

如果要将整个2d阵列转换为单个String,可以使用CSV类型编码,但是您必须保护任何特殊字符(例如逗号分隔符)搞乱场分离。一种快速(又脏的?)方法是对每个值使用enc = URLEncoder.encode(val, "UTF-8"),然后使用val = URLDecoder.decode(enc, "UTF-8")返回。

您还必须使用其他分隔符(例如\n)来分隔行:

String write(MyENum[][] myArray) {
    String res = "";
    for (int iRow = 0; iRow < myArray.length; iRow++) {
        for (int iCol = 0; iCol < myArray[iRow].length; iCol++)
            res += URLEncoder.encode(myArray[iRow][iCol].name(), "UTF-8")+",";
        res += "\n";
    }
}

(我告诉你不要在每一行的末尾添加额外的",")。然后,回头看看:

MyEnum[][] read(String res) {
    String[] rows = res.split("\n");
    MyEnum[][] myArray = new MyEnum[rows.length][];
    for (int iRow; iRow < rows.length; iRow++) {
        String[] cols = rows[iRow].split(",");
        myArray[iRow] = new MyEnum[cols.length];
        for (int iCol = 0; iCol < cols.length; iCol++)
            myArray[iRow][iCol] = MyEnum.valueOf(URLDecoder.decode(cols[iCol], "UTF-8"));
    }
    return myArray;
}

这完全基于以下事实:您的枚举中有name()valueOf()方法可用于转换,正如@ sean-f在他链接的帖子中显示的那样。