您的位置:首页 > Web前端

Java使用FileWriter和BufferedWriter添加内容到文件末尾

2017-01-10 14:31 393 查看
From: http://beginnersbook.com/2014/01/how-to-append-to-a-file-in-java/

/* 使用FileWriter 和 BufferedWriter将内容追加到文件末尾
*/

import java.io.*;

public class Exercise {

public static void main(String args[]) {
try {
String content =
"This is my content which would be appended " + "at the end of the specified file";
// Specify the file name and path here
File file = new File("/home/zjz/Desktop/myFile.txt");
// This logic is to create the file if the file is not already present
if (!file.exists()) {
file.createNewFile();
}
// Hrer true is to append the content to the file
FileWriter fw = new FileWriter(file, true);
// BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
// closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully appended at the end of file.");
} catch (IOException e) {
System.out.println("Exception occurred:");
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息