java I/O内存操作流

来源:互联网 发布:python usage 编辑:程序博客网 时间:2024/04/26 03:50

ByteArrayInputStream和ByteArrayOutputStream
ByteArrayInputStream包含一个内部缓冲区,该缓冲区包含从流中读取的字节,内部计数器跟着read方法要提供的下一个字节。
FileInputStream是把文件当做数据源。ByteArrayInputStream则是把内存中的某一个数组单做数据源。
ByteArrayOutputStream类实现了一个输出流。其中的数据被写入一个byte数组。缓冲区会随着数据的不断写入而自动增长。可使用toByteArray()和toString()获取数据源的。ByteArrayOutputStream将一个输出流指向一个Byte数组,但这个Byte数组是ByteArrayOutputStream内部内置的,不需要定义。


操作步骤




import java.io.* ;public class ByteArrayDemo01{    public static void main(String args[]){        String str = "HELLOWORLD" ;        // 定义一个字符串,全部由大写字母组成        ByteArrayInputStream bis = null ;    // 内存输入流        ByteArrayOutputStream bos = null ;    // 内存输出流        bis = new ByteArrayInputStream(str.getBytes()) ;    // 向内存中输出内容        bos = new ByteArrayOutputStream() ;    // 准备从内存ByteArrayInputStream中读取内容        int temp = 0 ;        while((temp=bis.read())!=-1){            char c = (char) temp ;    // 读取的数字变为字符            bos.write(Character.toLowerCase(c)) ;    // 将字符变为小写        }        // 所有的数据就全部都在ByteArrayOutputStream中        String newStr = bos.toString() ;    // 取出内容        try{            bis.close() ;            bos.close() ;        }catch(IOException e){            e.printStackTrace() ;        }        System.out.println(newStr) ;    }};

使用BufferedInputStream和BufferedOutputStream实现文件的复制void copyFile(String src , String dec){   FileInputStream fis=null;   BufferedInuptStream bis=null;    FileOutputStream fos=null;   BufferedOutputStream bos=null;   try {       fis=new FileInputStream(src);       fos=new FileOutputStream(dec);       bis=new BufferedInputStream(fis);       bos=new BufferedOutputStream(fos);       while ((temp=bis.read())!=-1) {           bos.write(temp);       }   } catch (FileNotFoundException e) {        e.printStackTrace();   }catch (IOException e) {        e.printStackTrace();   }finally {        //增加处理流后,注意流的关闭顺序!“后打开的先关闭”        try {            bos.close();        } catch (IOException e) {             e.printStackTrace();        }        try {            bis.close();        } catch (IOException e) {             e.printStackTrace();        }        try {            fos.close();        } catch (IOException e) {             e.printStackTrace();        }        try {            fis.close();        } catch (IOException e) {             e.printStackTrace();        }   }}


0 0
原创粉丝点击