美文网首页
初学Java,IO流中FileInputStream的new与r

初学Java,IO流中FileInputStream的new与r

作者: 石头时代zy | 来源:发表于2020-04-16 09:16 被阅读0次

    个人笔记:
    注意事项:
    1、new FileInputStream的时候需处理异常。
    2、每次使用流后都要关闭流,finally确保流的关闭时,需用if语句 if (fileInputStream != null)避免空指针异常。
    3、为确保流的关闭,声明FileInputStream在try外声明,并赋null。
    4、使用while循环进行改进read。
    5、一次阅读一个字节,效率低下,不建议使用。

    import java.io.FileInputStream;
            import java.io.FileNotFoundException;
            import java.io.IOException;
    
    public class Test{
        public static void main(String[] args)  {
            FileInputStream fileInputStream = null;
            //try...catch处理异常
            try {
                //创建FileInputStream对象
                fileInputStream = new FileInputStream("文件路径");
                int read = 0;
                //改进while循环,读到-1时终止
                while ((read = fileInputStream.read()) != -1){
                    //输出读到的字节
                    System.out.println(read);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //确保流关闭,避免空指针异常,用if语句
                if (fileInputStream != null){
                   //try...catch语句捕捉IO异常
                   try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:初学Java,IO流中FileInputStream的new与r

          本文链接:https://www.haomeiwen.com/subject/sgdlvhtx.html