字节流

|-- InputStream(读)

|-- OutputStream(写)

 

由于字节是二进制数据,所以字节流可以操作任何类型的数据,值得注意的是字符流使用的是字符数组char[]而字节流使用的是字节数组byte[]。下面来看一个字节流读写文件的简单例子。

清单7,使用字节流读写文本文件代码   

private static void test5(){ 

    FileOutputStream fos=null; 

    try{ 

        fos=new FileOutputStream("D:/test.txt"); 

        fos.write(0010);//写入二进制数据 

        fos.flush(); 

    }catch(IOException e){ 

         

    }finally{ 

        try{ 

            fos.close(); 

        }catch(IOException ex){ 

             

        } 

    } 

    FileInputStream fis=null; 

    try{ 

        fis=new FileInputStream("D:/test.txt"); 

        //fis.available()是获取关联文件的字节数,即test.txt的字节数 

        //这样创建的数组大小就和文件大小刚好相等 

        //这样做的缺点就是文件过大时,可能超出jvm的内存空间,从而造成内存溢出 

        byte[] buf=new byte[fis.available()]; 

        fis.read(buf); 

        System.out.println(new String(buf)); 

    }catch(IOException e){ 

         

    }finally{ 

        try{ 

            fos.close(); 

        }catch(IOException ex){ 

             

        } 

    } 

 

清单8,使用缓冲区对一张图片进行复制代码   

private static void test6(){ 

    BufferedOutputStream bos=null; 

    BufferedInputStream bis=null; 

    try{ 

        //前面已经说过了,缓冲对象是根据具体的流对象创建的,所以必须要有流对象  

        bis=new BufferedInputStream(new FileInputStream("E:\\images\\wo\\1.jpg")); 

        //写入目标地址 

        bos=new BufferedOutputStream(new FileOutputStream("E:\\test.jpg")); 

        byte[] buf=new byte[1024]; 

        while((bis.read(buf))!=-1){ 

            bos.write(buf); 

        } 

        bos.flush(); 

    }catch(IOException e){ 

        e.toString(); 

    }finally{ 

        try{ 

            if(bos!=null){ 

                bos.close(); 

            } 

            if(bis!=null){ 

                bis.close(); 

            } 

        }catch(IOException ex){ 

            ex.toString(); 

        } 

    } 

 

posted @ 2016-11-18 16:46  疯狂的tiger  阅读(297)  评论(0编辑  收藏  举报