将“deepToString()”转换回2D数组

时间:2015-10-16 09:10:36

标签: java arrays multidimensional-array

我想使用此方法将2D数组转换为字符串到属性文件中。然后,通过将属性字符串转换回2D数组,从属性中导入它。但是我很难将String转换回2D数组。

编辑:我想将2D数组字符串输出反转回2D数组。但是你给我的question并没有帮我解决2D阵列问题。由于Arrays.replace()无法替换2D数组的内部数组。

这是我的代码:

public static void getSettings(){
try {
File file = new File("config.properties");
Properties p = new Properties();
FileInputStream fileInput = new FileInputStream(file);
//Import
moduleNames = p.getProperty("moduleNames").split("");
moduleData = ??? //I don't know how to convert String to String[][]
}
catch (Exception e){
e.printStackTrace();
}
}

这是另一个设置属性的函数:

public static void writeFile(String[][] mD, String[] mN){
try{
Properties p = new Properties;
File file = new File("config.properties");

p.setProperty("moduleData", Arrays.deepToString("mD"));
p.setProperty("moduleNames", Arrays.toString("mN"));
//...further more code to flush the data out
} catch (Exception e){
e.printStackTrace();
}

}

有谁能告诉我如何将String(从deepToString)转换回String [] []?

我的项目是开源的。这个:Conf.java Line271是设置属性。

而且:Conf.java Line215是String [] [] one的加载字符串。

1 个答案:

答案 0 :(得分:0)

我找不到任何能够做到这一点的标准方法。但是使用here中的想法,我已经制定了以下内容:

        String[][] sample = new String[][]{{"Apple", "Ball"},{"Cat", "Dog"}, {"Elephant, Fish"} };
        String temp = Arrays.deepToString(sample);
        String[] strings = temp.replace("[", "").replace("]", ">").split(", ");
        List<String> stringList = new ArrayList<>();
        List<String[]> tempResult = new ArrayList<>();
        for(String str : strings) {
            if(str.endsWith(">")) {
               str = str.substring(0, str.length() - 1);
               if(str.endsWith(">")) {
                   str = str.substring(0, str.length() - 1);
               }
               stringList.add(str);
               tempResult.add(stringList.toArray(new String[stringList.size()]));
                stringList = new ArrayList<>();
            } else {
                stringList.add(str);
            }
        }
       String[][] originalArray = tempResult.toArray(new String[tempResult.size()][]);

这有很大的改进空间,我希望你能做到这一点。这仅用于将String转换回2D数组的提示。

相关问题