File file = new File("d:\\file.txt");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("\r\n" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "\r\n" +str + "\r\n------------------------------------------------------");
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
说明:
- FileWriterfw = new FileWriter(file, true); 第二个参数true代表可以追加写入文件,需要覆盖写入时使用new FileWriter(file)即可。‘
- "\r\n":换行符