Curlip
Curlip

Reputation: 395

Writing a 2D Array to a string, then to a .txt file - Java

I have a Method that calls a second method, the second method will:

First method

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

Second Method (Not all code just relevant code)

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;
    }
}

Call to the first method

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();
}

I cant find why this won't work. I think it has to do with the second method, particularly

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

Thanks if anyone can help me.

Curlip

Upvotes: 0

Views: 152

Answers (1)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

Try this if you want to just convert an array of strings into a single string:

    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

BTW, your loop condition seems wrong and ,so you may change it to :

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

Upvotes: 2

Related Questions