Java中的“流”的flush方法

来源:互联网 发布:淘宝技术排查异常订单 编辑:程序博客网 时间:2024/06/05 09:58

在练习PrintWriter输出流时,出现一个问题,如下面的代码

public class inputStreamExercise {    public static void main(String[] args) {        String s=null;        try{            BufferedReader br=                    new BufferedReader(new InputStreamReader(System.in));            FileWriter fw=                    new FileWriter("E:/java/test/test4.txt",true);            PrintWriter pw=                    new PrintWriter(fw);            while((s=br.readLine())!=null){                if(s.equalsIgnoreCase("exit")) break;                pw.write(s.toUpperCase());                System.out.println(s);                pw.println(s);                pw.print(" "+new Date(1)+" ");                pw.flush();//如果不加这句话,文件中就没有数据!!!            }            pw.flush();            pw.close();        }catch(IOException e){            e.printStackTrace();        }

System.in负责从控制台输入数据,然后通过PrintWriter处理流和FileWriter节点流依次读入到文件text4 中去。但是,如果在while循环中没有加pw.flush(),那么数据就不会被写入到文件中。flush方法是用于将输出流缓冲的数据全部写到目的地。
所以一定要在关闭close之前进行flush处理,即使PrintWriter有自动的flush清空功能。

0 0