Java文件与io——缓冲流

对文件或其它目标频繁的读写操作,效率低,性能差。

使用缓冲流的好处,能够更高效的读写信息,原理是将数据先缓冲起来,然后一起写入或者读取出来。

BufferedInputStream:为另一个输入流添加一些功能,在创建时,会创建一个内部缓冲区数组,用于缓冲数据

BufferedOutputStream:通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统

BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。

public class BufferedStreamDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        byteStreamOut();
        byteStreamIn();
        charStreamOut();
        charStreamIn();
    }
    //BufferedOutputStream
    public static void byteStreamOut(){
        try {
            OutputStream out=new FileOutputStream("G:\\hhb.txt");
            BufferedOutputStream bos=new BufferedOutputStream(out);
            bos.write("hhhhh".getBytes());
            bos.close();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    //BufferedInputStream
    public static void byteStreamIn(){
        try {
            InputStream in=new FileInputStream("G:\\hhb.txt");
            BufferedInputStream bis=new BufferedInputStream(in);
            byte[] bytes=new byte[1024];
            int len=-1;
            StringBuffer sb=new StringBuffer();
            while((len=bis.read(bytes))!=-1){
                sb.append(new String(bytes, 0, len));
            }
            bis.close();
            in.close();
            System.out.println(sb);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //BufferedWriter
    public static void charStreamOut(){
        try {
            Writer w=new FileWriter("G:\\hhh.txt");
            BufferedWriter bw=new BufferedWriter(w);
            bw.write("我爱你!");
            bw.close();
            w.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //BufferedReader
    public static void charStreamIn(){
        try {
            Reader r=new FileReader("G:\\hhh.txt");
            BufferedReader br=new BufferedReader(r);
            char[] c=new char[1];
            int len = -1;
            StringBuffer sb=new StringBuffer();
            while((len=br.read(c))!=-1){
                sb.append(c,0,len);
            }
            br.close();
            r.close();
            System.out.println(sb);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                
    }
}

 

posted on 2016-01-10 10:00  深海溺心  阅读(293)  评论(0编辑  收藏  举报

导航