public class FileWriterDemo {
//获取系统中的换行
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static void main(String[] args) throws IOException {
//创建一个输出对象,决定是否可以追加
FileWriter fw = new FileWriter("test.txt",true);
//写入东西,到临时缓存区
fw.write("ads"+LINE_SEPARATOR+"fdd");
//追加,否则覆盖
fw.write("append");
//刷新,写入内存
//fw.flush();
//close操作会自动先刷新
fw.close();
}
}
对于异常的处理
public class FileWriterDemo2 {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static void main(String[] args){
//try外创建try里初始化
FileWriter fw = null;
try {
fw = new FileWriter("k:\\test.txt",true);
fw.write("ads"+LINE_SEPARATOR+"fdd");
} catch (Exception e) {
System.out.println(e.toString());
//一定要关闭
}finally{
//防止空指针异常
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
throw new RuntimeException("fail close");
}
}
}
}