为什么要说这个类,有时候我们可能需要把一些信息追加写入文件中(比如打印的日志)

Flushable 刷新数据到目的地,可以调用flush把缓冲区数据刷入到底层流
appendable作用 追加数据到目的地
try (FileWriter writer = new FileWriter("desc",true)){ //为true开启追加模式
writer.write("你好\r\n"); //linux 要换行为 \r
}catch (Exception e){
e.printStackTrace();
}
看下具体实现,具体在构造函数中打开这个开关
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
this.fd = new FileDescriptor();
fd.attach(this);
this.append = append;
this.path = name;
open(name, append); //打开文件追加模式开关
}
private native void open0(String name, boolean append) //底层本地方法实现
throws FileNotFoundException;
本文介绍了如何使用Java中的FileWriter进行文件追加操作,并解释了追加模式的实现原理。通过具体的代码示例,展示了如何开启追加模式并写入数据。
662

被折叠的 条评论
为什么被折叠?



