【JAVA-IO流-字节读取】

1.概述

当需要进行数据的传输时可以使用IO流进行,将磁盘中的数据传输到内存,或从网络读取到内存中。
IO流根据处理数据类型不同分为字符流和字节流,又根据流向不同,分为流入和流出,对流入对象只能进行读操作,流出对象只能进行写操作。

数据类型顶层父类
字节流(输入)Java.io.InputStream
字节流(输出)Java.io.OnputStream
字符流(输入)Java.io.Reader
字符流(输出)Java.io.Writer

2.字节输入流

FileInputStream用来读取文件数据的字节输入流

2.1构造方法
 //传入文件路径创建流对象  抛出异常
        FileInputStream inputStream1 = new FileInputStream("F:\\IDEA\\code\\test\\1.txt");
//        System.out.println(inputStream1);

        //传入文件路径的File对象创建流对象
        File file = new File("F:\\IDEA\\code\\test\\1.txt");
        FileInputStream inputStream2 = new FileInputStream(file);

2.2一次读入一个字节
/*
        一次读入一个字节:public int read() throws IOException
        当所有字节读入完成以后,返回值为-1,可以以此为依据进行循环读出所以字节
         */
        int read = 0;
        while((read = inputStream1.read())!=-1){
            System.out.println(read);
        }
2.3一次读入一个字节数组
 /*
        一次读入一个字节数组:public int read(byte b[]) throws IOException
        传入一个字节数组,最多读取一个字节数组的数据,并且会把数据存入到数组中
        返回值代表本次读取到的字节的个数
        与read()相同,当所有数据读取完成以后,返回值为-1
         */
        byte[] bytes = new byte[10];
        int read1 = inputStream2.read(bytes);//返回读取字节的长度
        String s = new String(bytes, 0, read1);//将所有字节数组转换为字符串
        System.out.println(s);
        //当文件字节数过多时,需要读取到多个字节数组中,以此需要循环读入时
        byte[] bytes1 = new byte[2];
        int len;
        while ((len=inputStream2.read(bytes1))!=-1){
            System.out.println(new String(bytes1,0,len));//限制有效长度,为了最后没有填满数组是,读取有效值
        }


**注意1:**在读入的最后要进行资源释放

 inputStream1.close();
 inputStream2.close();

**注意2:**读取过程中进行了异常抛出

public static void main(String[] args) throws IOException {
}

3.资源释放

当不进行异常抛出是,怎么进行资源释放,这里仅展示的是JDK7版本,使用try…cash…resource的写法。在try后面加()。把需要释放的资源在小括号中定义,就不需要自己去释放资源了。

public static void main(String[] args) {
        try( FileInputStream inputStream1 = new FileInputStream("F:\\IDEA\\code\\test\\1.txt");){
             /*
        一次读入一个字节:public int read() throws IOException
        当所有字节读入完成以后,返回值为-1,可以以此为依据进行循环读出所以字节
         */
            int read = 0;
            while((read = inputStream1.read())!=-1){
                System.out.println(read);
            }
            inputStream1.close();//会自动执行释放资源的功能
        }catch (IOException e){

        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值