Reputation: 211
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?
Upvotes: 0
Views: 7409
Reputation: 1
Each time in the for loop you are creating a new FileWriter & BufferedWriter object which is not good
Upvotes: 0
Reputation: 185
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();
}
Upvotes: 1