java I/O内存操作流

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值