java IO注意事项

来源:互联网 发布:大学软件开发专业课程 编辑:程序博客网 时间:2024/06/15 08:07

FIleWriter中的flush和close方法


当你向一个文件中写入数据时,如何没有使用输出流的close或者flush方法,会导致数据写不进去;


原因:file writer中也有缓冲区域,使用write方法只是将数据写入到内存缓冲中,并没有写入到文档中,而调用flush方法就可以将缓冲区的数据写入到文档中,使用close也有同样的作用,只不过close可以节省内存,如果总是调用流而不关闭,将会导致内存泄露,导致程序崩溃;



源程序;

import java.io.*;
public class App10_9 {

    public static void main(String[] args) throws IOException{
    File f=new File("C:\\Users\\WUWENXIANG\\Desktop\\test.java");
    FileReader fr=new FileReader(f);
    
    
    File f1=new File("C:\\Users\\WUWENXIANG\\Desktop\\cp.txt");
    FileWriter fw=new FileWriter(f1);
    int a=0;
    
    while((a=fr.read())!=-1)
    
        //System.out.print((char)a);
    fw.write(a);
    fw.flush();
    //fw.close();   //输出流必须关闭才能保证数据写入
    fr.close();

    
    

    }

}


0 0
原创粉丝点击