FileInputStream的使用

从硬盘存在的一个文件中,读取其内容到程序中,使用FileInputStream

代码

@Test
public void testFileInputStream1() throws IOException {
    //1. 创建一个File类的对象
    File file = new File("hello.txt");
    //2. 创建一个FileInputStream类的对象
    FileInputStream fileInputStream = new FileInputStream(file);

    //3. 调用fileInputStream的方法,实现file文件的读取
    //read():读取文件的一个个字节 当执行到文件结尾时返回-1
    //int read = fileInputStream.read();
    //while (read != -1){
    //    System.out.println(read);
    //    read = fileInputStream.read();
    //}

    //精简版本
    int b;
    while ((b = fileInputStream.read())!= -1){
        System.out.print((char) b);
        System.out.println();
    }
    //4. 关闭相应的流
    fileInputStream.close();
}

修改版本使用 try-catch的方式处理异常更加合理,保证流的关闭操作一定能够执行

@Test
public void testFileInputStream2(){
    //1. 创建一个File类的对象
    File file = new File("hello.txt");
    FileInputStream fileInputStream = null;
    try {
        //2. 创建一个FileInputStream类的对象
        fileInputStream = new FileInputStream(file);
        //精简版本
        int b;
        while ((b = fileInputStream.read())!= -1){
            System.out.print((char) b);
            System.out.println();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        //3. 关闭相应的流
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}

开发中使用的方式

@Test
public void test3() {
    FileInputStream fis = null;
    try {
        File file = new File("hello1.txt");
        fis = new FileInputStream(file);
        byte[] bytes = new byte[5];  //读取到数据要写入数组
        int len;    //每次读入到byte中的字节的长度
        while ((len = fis.read(bytes)) != -1){
            //for (int i = 0; i < bytes.length; i++) {
            //    System.out.print((char) bytes[i]);
            //}
            String str = new String(bytes, 0, len);
            System.out.print(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}