InputStream

InputStream表示字节输入流的父类,这是个抽象类,我们可以使用其子类FileInputStream

InputStream in = null;
    try {
        //1、创建一个输入流(字节输入)跟文件关联
        in = new FileInputStream("E:\\abc\\123.txt");
        int content;
        //2、读取内容
        while ((content = in.read()) != -1) { // 如果读到末尾会返回-1
            // 处理读出来的内容
            System.out.print((char) content);
        }
        // 读完了
    }catch(Exception e){

    }finally{
        //3、关闭流
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

第二种读取方式:自定义一个缓冲大小(读的过程)

//用byte数组来定义缓冲区
    byte[] buffer = new byte[1024];
    int num;
    while ((num = in.read(buffer)) != -1) {
        //处理数据... 数据在buffer中从0-num有效
    }
OutputStream

将内容从程序中写到文件中

//1、创建一个输出流(跟文件关联通道)
    OutputStream out = null;
    try {
        //输出的目标文件夹一定要存在
        out = new FileOutputStream("E:\\abc\\456.txt");
        String str = "Hello123";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            //将内容按字节写到文件中
            out.write(c);
        }
        //写完了
        System.out.println("写完了");
    }catch(Exception e){

    }finally{
        //关闭流
        out.close();
    }
缓冲流

辅助流,字节输入有BufferenInputStream,字节输出BufferedOutputStream,使用方式:套在原始流上

InputStream in = null;
    BufferedInputStream bi = null;
    // 缓冲输出流
    BufferedOutputStream bOut = null;
    ...
    // 直接对接磁盘
    in = new FileInputStream("E:\\abc\\123.txt");
    // 输入流上加缓冲流
    bi = new BufferedInputStream(in);
    bOut = new BufferedOutputStream(new FileOutputStream("E:\\abc\\def\\hello.txt"));
        //读写操作跟普通流一样

注意:缓冲输出流在关闭之前建议加上flush

bOut.flush();
bOut.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值