Java – instead of rewriting, new files are created
•
Java
I am trying to write to an existing file As I saw on the forum, this code should rewrite the old file, but not rewrite it. Instead, put the file name in [] brackets and create a new file Any ideas?
try {
File file = new File("/home/erik/glassfish3/" + selectedMss + ".ini");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
for (String newline : content) {
output.write(newline + "\n");
}
output.close();
} catch (IOException e) {
e.printStackTrace();
}
Solution
The filewriter class has a constructor that accepts a second Boolean parameter that specifies whether the writer should use an append mode that appends new content to the end of an existing file
I also recommend closing the writer in the finally block
Documentation
BufferedWriter output;
try {
File file = new File("/home/erik/glassfish3/"+selectedMss+".ini");
//Providing true for second argument specifies it should be appended.
output = new BufferedWriter(new FileWriter(file,true));
for(String newline: content){
output.write(newline+"\n");
}
} catch ( IOException e ) {
e.printStackTrace();
}finally{
output.close();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
