JAVA I/O

使用流有4个步骤:

1.确定对象

2.打开流

3.操作流

4.关闭流

1.确定对象

public class Main {
    public static void main(String[] args) {
        String pathName = "D:/i.txt";
        byte[] bytes = new byte[4];
    }
}

“abcdef123456”这个是我存在D:/i.txt中的内容。

String pathName = "D:/i.txt";这个使用来确定对象的;byte[] bytes = new byte[4];当流打开后需要开辟一块空间来储存流入的数据,不然当流打开,流入的数据就必须马上处理,这个就有了缓存的作用可以提高效率,增大数组的大小就可以提高流入的速度。

2打开流

public class Main {
    public static void main(String[] args) {
        String pathName = "D:/i.txt";
        byte[] bytes = new byte[4];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(pathName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

这个就打开了流,但是在这里就先把关闭流写上去了,为了防止后来忘记,提前写可以防止出错。

将FileInputStream fis = new FileInputStream(bytes);分开写是因为作用域的原因,如果都写在try中后面就不可以关闭流了。

3.操作流

public class Main {
    public static void main(String[] args) {
        String pathName = "D:/i.txt";
        byte[] bytes = new byte[4];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(pathName);
            int read = fis.read(bytes);
            for (int i = 0;i < bytes.length;i++){
                System.out.println(bytes[i]);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

现在将文件中读到的内容存到了bytes数组中,但是文件的内容比bytes大,所以只是我储存了4个字节的内容 但是文件中的内容全都流入了内存中。

public class Main {
    public static void main(String[] args) {
        String pathName = "D:/i.txt";
        byte[] bytes = new byte[4];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(pathName);
            int read;
            while ((read = fis.read(bytes))!= -1 ){
                for (int i = 0;i < bytes.length;i++){
                    System.out.println(bytes[i]);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

这样就可以打印出所以的内容了。(read = fis.read(bytes))!= -1用这个判断是否停止时因为在read方法中当读取到最后的时候会返回-1,所以当read=-1就会停止。

4.关闭流 这个在打开流的时候就写好了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值