JAVA 篇之IO FileWrite

本文介绍了如何使用Java中的FileWriter进行文件追加操作,并解释了追加模式的实现原理。通过具体的代码示例,展示了如何开启追加模式并写入数据。

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

225711_RqhL_2663859.png

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;

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/chenping12/blog/1480287

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值