将2D数组写入字符串,然后写入.text文件 - Java

时间:2014-04-18 07:08:15

标签: java string file multidimensional-array

我有一个方法调用第二个方法,第二个方法将:

  • 创建任何缺少的目录
  • 创建文件
  • 将2D String []解码为String(不工作)
  • 撰写内容
  • 将解码后的字符串写入带有标题(不工作)的文件

第一种方法

public static boolean store(Exception exception, String[][] flags){
    return storePrivate(exception, location, flags);
}

第二种方法(并非所有代码都只是相关代码)

private static boolean storePrivate(Exception exception, String dir, String[][] flags){
    String flag = "";

    for(int i = 0; i >= flags.length; i++){
        flag = flag + "" +  flags[i][0] + ": " + flags[i][1] + "\n";
    }
    try {
        File directory = new File(dir);
        File file = new File(dir + id + ".txt");
        if (!directory.exists()) {
            directory.mkdirs(); 
        }
        file.createNewFile();
        FileWriter filewriter = new FileWriter(file.getAbsoluteFile());
        BufferedWriter writer = new BufferedWriter(filewriter);


        if(flag != ""){
            writer.write("Flags by Developer: ");
            writer.write(flag);
        }   
        writer.flush();
        writer.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

调用第一种方法

public static void main(String[] args) {
    try {
        test();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        ExceptionAPI.store(e, new String[][]{{"flag1", "Should be part of flag1"}, {"flag2", "this should be flag 2 contence"}});
    }
}

public static void test() throws IOException{
    throw new IOException();
}

我无法找到为什么这不会起作用。我认为这与第二种方法有关,特别是

if(flag != ""){
    writer.write("Flags by Developer: ");
    writer.write(flag);
}  

谢谢,如果有人可以帮助我。

Curlip

1 个答案:

答案 0 :(得分:2)

如果您只想将字符串数组转换为单个字符串,请尝试此操作:

    String[] stringTwoD = //... I think this is a 1D array, and Sting[][] is a 2D, anyway
    String stringOneD = "";
    for (String s : stringTwoD) 
        stringOneD += s;//add the string with the format you want
顺便说一下,你的循环条件似乎不对,所以你可以把它改成:

for(int i = 0; i < flags.length; i++){
    flag += flags[i][0] + ": " + flags[i][1] + "\n";
}