*字节流与字符流3(InputStream)

如果程序要进行数据读取的功能,可以使用InputStream类功能。

public abstract class InputStream
extends Object
implements Closeable

虽然与OutputStream一样继承了Closeable接口,但是一样不用去考虑此接口的存在,此类提供3个方法读取的方法:
读取单个字节:

public abstract int read()
                  throws IOException

返回值:返回读取的字节内容,如果现在已经没有内容了,如何用int型表示内容为空呢?没有数据可读,用-1表示。循环过程使用while条件循环。

将读取的数据保存在字节数组里:

public int read(byte[] b)
         throws IOException

返回值:返回读取的数据长度,但是如果已经读取到结尾了,返回-1

将文件中读取的数据保存在部分字节数组里:

public int read(byte[] b,
       int off,
       int len)
         throws IOException

返回值:读取的部分数据的长度,如果已经读取到结尾了,返回-1.

范例:向数组里面读取数据

package TestDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;




public class TestDemo{
    
    public static void main(String[] args) throws Exception{
        //1.定义要输入的文件目录
        File file=new File("e:"+File.separator+"demo"+File.separator+"my.txt");
        //如果文件存在才可以进行读取
        if(file.exists()){//文件存在
            //2.使用InputStream进行读取
            InputStream input=new FileInputStream(file);

            //3.进行数据读取
            byte data[]=new byte[1024];//准备出一个1024的字节数组
            int len=input.read(data);//将读取的内容保存到字节数组中

            //4.关闭输入流
            input.close();
            System.out.println(new String(data,0,len));
        }
    }   

}
9003228-153cfcc91fb75e85.png
image.png

范例:单个字节进行读取
由于一个文件含有多个字节数据,如果要读取肯定要采用循环的方式完成,由于不确定循环次数,所以应该使用while循环完成,下面为了更好的演示出问题,使用do while与while两种方式实现。
do while(掠过)
while实现:(重点)

package TestDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;




public class TestDemo{
    
    public static void main(String[] args) throws Exception{
        //1.定义要输入的文件目录
        File file=new File("e:"+File.separator+"demo"+File.separator+"my.txt");
        //如果文件存在才可以进行读取
        if(file.exists()){//文件存在
            //2.使用InputStream进行读取
            InputStream input=new FileInputStream(file);

            //3.进行数据读取
            byte data[]=new byte[1024];//准备出一个1024的字节数组
            int foot=0;//表示字节数组的操作角标
            int temp=0;//表示每次接收的字节数据
            while((temp=input.read())!=-1){
                data[foot]=(byte) temp;
                foot++;
            }

            //4.关闭输入流
            input.close();
            System.out.println(new String(data,0,foot));
        }
    }   

}
9003228-46288b35c2ff7af2.png
image.png

此类数据读取的方式在以后的开发中是使用最多的情况。所以一定要掌握

猜你喜欢

转载自blog.csdn.net/weixin_34315189/article/details/87040373