首先说明,如果有中文字符,需要处理中文编码问题
第一种写法,覆盖原文件内容:
public static void writeFile(String filePath, String fileName, String context) throws IOException {
FileOutputStream fileOutputStream = null;
File file = new File(filePath + fileName);
if(!file.exists()){
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(context.getBytes("utf-8"));
fileOutputStream.flush();
fileOutputStream.close();
}
第二种写法,在原文件内容后追加
public static void writeFile(String filePath, String fileName, String context) throws IOException {
String path = filePath + fileName;
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path,true)));
out.write(context);
out.close();
}