字节流

|-- InputStream(读)数组

|-- OutputStream(写)jvm

 

因为字节是二进制数据,因此字节流能够操做任何类型的数据,值得注意的是字符流使用的是字符数组char[]而字节流使用的是字节数组byte[]。下面来看一个字节流读写文件的简单例子。spa

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

private static void test5(){ 对象

    FileOutputStream fos=null; 图片

    try{ 内存

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

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

        fos.flush(); test

    }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(); 

        } 

    }