java如何追加写入txt文件

来源: https://zhidao.baidu.com/question/753882151724406604.html

方法一:

public static void method2(String file, String conent) {
	BufferedWriter out = null;
	try {
	out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
	out.write(conent+"\r\n");
	} catch (Exception e) {
	  e.printStackTrace();
	} finally {
	   try {
	     out.close();
	    } catch (IOException e) {
	       e.printStackTrace();
	    }
       }
}

方法二:

public void method1() {
FileWriter fw = null;
try {
//如果文件存在,则追加内容;如果文件不存在,则创建文件
File f=new File("E:\\dd.txt");
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println("追加内容");
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}


你可能感兴趣的:(JAVA)