将字节输入到流和输入到缓冲区有什么区别_Java之IO流

67c3e0add5603d739ffdefae45b80164.png

IO流及其概述和分类

一:IO流用来处理数据之间的传输,Java对数组的数据是用流的方式,Java用于操作流在IO包中
二:流可以分为输入流,和输出流
三:操作类型可以分为:①字节流字节流可以操作任何数据,因为计算机中任何数据都是以字节存在的 ②:字符流可以操作存在的字符流,这样比较方便
四:IO流的分类 ①InputStream ②OutputStream 字符流的抽象对象 Reader Writer
五:IO程序的书写 ①使用前,导IO包 ②使用时进行IO异常处理 ③使用后释放资源

//创建输入流对象
        FileInputStream fs=new FileInputStream(“bb.txt”);
        int b;
        //读流的过程
        while((b=fs.read())!=-1){
            System.out.print(b);
        }
        //切记要记得关流
        fs.close();

为啥要用int值去接受

因为输入流可以操作任意文件,包括图片,音频等,这些文件都是已二进制形式存储在,如果每一次读取文件都是返回的11111111,是-1的补码就会停止不读了,后面的数据读不到,所以就用int数据去接受。

数组拷贝available方法

//在开发中不推荐使用
//创建输入输出对象
  FileInputStream fis=new FileInputStream("Ea.txt");
  FileOutputStream fos=new FileOutputStream("E:b.txt");
 //把要读取的数据放在数组中
 byte by= new byte[fis.available];
 //读文件
 fis.read(by);
 //写文件
 fos.write(by);
   fis.close();
   fos.close();

创建字节缓存流

BufferedInputStream bri=new BufferedInputStream(new FileInputStream("aa.txt"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("bb.txt"));
int c;
while((c=bri.read())!=-1){
    bos.write(c);
}
bri.close();
bos.close();

close和flush的刷新的区别

//close具有刷新功能,在关闭流之前,就会先刷新一次缓冲区,将缓冲区字节全部都刷新在缓冲区上,在关闭close刷完后不能写了
 flush方法?
 具备刷新功能,刷完后还可以继续写
  FileInputStream filei = new FileInputStream("E:rec.avi");
        //创建输出流对象
        FileOutputStream fileo = new FileOutputStream("E:copy1.avi");
         byte arr[]=new byte[1024*8];
         int len;
         while ((len=filei.read(arr))!=-1){
             fileo.write(arr);
         }
         //close具有刷新功能,在关闭流之前,就会先刷新一次缓冲区,将缓冲区字节全部都刷新在缓冲区上,在关闭
         filei.close();
         fileo.close();

7cbde777ffc6a830ac5be966068c8c1c.png

练习

在控制台输入文件路径, 将文件拷贝到当前目录下

public static void main(String [] args){
//创建字符缓冲区
   BufferedInputStream bis=new BufferedInputStream(new FileInputStream(getFile()));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(getFile().getName()));
int b;
while((b=bis.read())!=-1){
    bos.write(b);
}
bis.close();
bos.close();
//用getFile方法区封装要获取的路劲
public static File getFile(){
    Scanner sc=new Scanner(System.in);
System.out.print("重键盘上输入路径");
    while(true){
        String line=sc.nextLine();
        File dir=new File(line);
        //增加程序的鲁邦性
        if(!dir.exists()){
            System.out.print("你输入的路径不存在");
        }else if(dir.isDirectory){
            System.out.print("你输入文件目录,请重新输入");
        }else{
            retrun file;
        }
        }
    }
} 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值