字节流读数据演示示例

fos.txt文件内容:

public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        //创建字节输入流对象
        FileInputStream fis = new FileInputStream("myFile\\fos.txt");

        //调用字节输入流对象的读数据方法
        //第一次读取
        int by = fis.read();
        System.out.println(by);  //97
        System.out.println((char)by);  //a
        
        //第二次读取
        by=fis.read();
        System.out.println(by);  //98
        System.out.println((char)by);  //b
    }
}

通过两次调用读取方法,发现代码过于重复,能否使用循环改进呢?如果要使用循环就要知道循环的终止条件的是什么,通过帮助文档查看可以知道,读取到流的末尾时,将返回-1

通过循环改进读取:

修改fos.txt:

 改进后的代码:

//通过循环改进读取数据
        int by;
        while ((by=fis.read())!= -1){
            System.out.print((char)by);
        }

        //释放资源
        fis.close();

运行结果:

猜你喜欢

转载自www.cnblogs.com/pxy-1999/p/12704429.html