io write Java_JAVA 篇之IO FileWrite

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

Flushable 刷新数据到目的地,可以调用flush把缓冲区数据刷入到底层流

appendable作用 追加数据到目的地

try (FileWriter writer = new FileWriter("desc",true)){ //为true开启追加模式

writer.write("你好 "); //linux 要换行为

}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;

为什么要说这个类,有时候我们可能需要把一些信息追加写入文件中(比如打印的日志) Flushable 刷新数据到目的地,可以调用flush把缓冲区数据刷入到底层流 appendable作用 追加数据到目的地 try (FileWriter writer = new FileWriter("desc",true)){ //为true开启追加模式 writer.write("你好 "); //linux 要换行为 }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;
经验分享 程序员 微信小程序 职场和发展