Question

I have a list of some commands stored in an ArrayList and I have been trying to get this list printed in a text file. Below is the code-

try {
    FileWriter writer = new FileWriter("Commands.txt");
        for(String str: commandArray){
        writer.write(commandArray[i]);
    }
 }
catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 

I get no errors but the file isn't created either. Is there something I have done wrong. Any help is appreciated. Many thanks.

EDITED QUESTION

@Sajal Dutta, I took your advice and came up with the following;

try {

    for(String str: movementArray){

        File file = new File("D://filename.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(str);
        bw.close();
    }
}

catch (IOException e) {
    e.printStackTrace();
}

At The moment the file is created, but only the last value of from the arraylist is printed to the file. There are six values stored in the arraylist, how do I get all six of the to print out?

Was it helpful?

Solution

You are missing-

finally {
    writer.close();
}

OTHER TIPS

try {
                if(!file.exists())
                    file.createNewFile();
                FileWriter writer = new FileWriter(file);
                BufferedWriter bw = new BufferedWriter(writer);
                for(String str : data){
                    bw.append(str);
                    bw.append("\n");
                }
                bw.close();
                writer.close();
            }

Each time in the for loop you are creating a new FileWriter & BufferedWriter object which is not good

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top