I have the following function for writing to a file:
public void writeToFile(String data) throws IOException {
FileWriter fstream = null;
try {
fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(data);
//Close the output stream
out.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fstream.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
What it does every time it is开发者_运维问答 called it creates a new file and writes a new line. What I want to achieve is to check whether file exist. If not create a new file and write something, if exists then open the file and add a new line without erasing existing text. How to do that?
change your FileOutputStream constructor call to this:
fstream = new FileWriter("out.txt", true);
FileWriter takes in an additional parameter for appends, which specifies if you want to create a new file or append to an existing file
fstream = new FileWriter("out.txt", true);
http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)
As there is a constructor in java's FileWriter class that can get an bool that idicates if the next "entry" is appended to the file, you should chage your
fstream = new FileWriter("out.txt");
to
fstream = new FileWriter("out.txt", true);
You can look up all those constructors in the java documentation: http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html
精彩评论