对于OutputStream 类,如果最后忘记关闭输出流,即没有写out.close();数据也会写入到文件之中。
而Writer类如果忘记关闭输出流,则数据不会写入到文件之中。如果不想关闭输出流,也可以使用flush()方法,将缓存中的数据清空,即写入到文件之中。程序如下:
import java.io.*; public class ooDemo06 { public static void main(String[] args){ //1.新建一个File类,找到要操作的文件 File f = new File("E://gzg.txt"); //2.新建一个父类Writer类,并通过子类实例化 Writer out = null; try { out = new FileWriter(f); } catch (IOException e) { e.printStackTrace(); } //3. 向文件中写入数据 String str = "我爱你中国,亲爱的母亲。。。"; try { out.write(str); out.flush();//如果不关闭输出流,也可以使用flush()方法清空缓存 } catch (IOException e) { e.printStackTrace(); } //4.关闭写入流 // try { // out.close(); // } // catch (IOException e) { // e.printStackTrace(); // } // } } |