Java基础巩固系列 FileInputStream(字节输入流)

代码示例:

/*
 * 1.流的分类:
 *   按照数据流向的不同:输入流 输出流
 *   按照处理数据的单位的不同: 字节流 字符流(处理的文本文件)
 *   按照角色不同:节点流(直接作用于文件的)  处理流
 *
 * 2.IO的体系:
 *   抽象基类            节点流
 *   InputSteam       FileInputStream
 *   OutputSteam      FileOutputStream
 *   Reader           FileReader
 *   Writer           FileWriter
 * */
public class TestIOStream {


    @Test
    public void testFileInputStream3() {
        FileInputStream fis = null;
        try {
            File file = new File("hello.txt");
            fis = new FileInputStream(file);
            byte[] b = new byte[5]; //读取到的数据要写入的数组
            int len; //每次读入到byte中的字节的长度
            while ((len = fis.read(b)) != -1) {
//                for (int i = 0; i < len; i++) {   //千万不能用b.length 不然会全部读出abcde fgcde
//                    System.out.print((char) b[i]);
//                }
                String str = new String(b,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //使用try-catch的方式处理如下的异常更合理:保证流的关闭操作一定可以执行
    @Test
    public void testFileInputStream2() {
        FileInputStream fis = null;
        try {
            //1.创建一个File类的对象
            File file = new File("hello.txt");
            //2.创建一个FileInputStream类的对象
            fis = new FileInputStream(file);
            //3.调用FileInputStream的方法,实现file文件的读取
            int b;
            while ((b = fis.read()) != -1) {
                System.out.print((char) b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭相应的流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //从硬盘存在的一个文件中,读取其内容到程序中,使用FileInputStream
    //要读取的文件一定要存在,否则抛FileNotFoundException异常
    @Test
    public void testFileInputStream1() throws IOException {
        //1.创建一个File类的对象
        File file = new File("hello.txt");
        //2.创建一个FileInputStream类的对象
        FileInputStream fis = new FileInputStream(file);
        //3.调用FileInputStream的方法,实现file文件的读取
        /*
         * read(): 读取文件的一个字节。当执行到文件结尾时,返回-1  bbacdef
         * */
//        int b = fis.read();
//        while (b != -1){
//            System.out.print((char) b);
//            b = fis.read();
//        }
        int b;
        while ((b = fis.read()) != -1) {
            System.out.print((char) b);
        }
        //4.关闭相应的流
        fis.close();
    }

}

test1结果:

abcdefg

test2结果:

abcdefg

test3结果:

abcdefg

猜你喜欢

转载自blog.csdn.net/Peter__Li/article/details/89021645
今日推荐