字节流的处理细节

最近学习了关于流的处理,及时的巩固,满满的都是细节。

public static void main(String[] args){
        // TODO Auto-generated method stub

        //在关于流的处理代码中,遇到异常最好不要直接抛出,虽然这样并不会报错,但是不利于后期代码的维护,
        //应该处理异常

        FileInputStream in = null;//定义的时候最好是写出“=null” 不要直接是FileInputStream in
        FileOutputStream out = null;
        FileOutputStream out1 = null;

        try {

            in = new FileInputStream("D:\\FileDemo\\demo\\b.txt");
            out = new FileOutputStream("D:\\FileDemo\\demo\\demo1\\m.txt");
            out1 = new FileOutputStream("D:\\FileDemo\\demo\\demo1\\n.txt");

            //单字节读取
            int a;
            while ((a = in.read()) != -1) { //返回:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
                out.write(a);               //一次读取一个字节
            }

            //多字节读取
            int len;
            byte [] b = new byte[512];      //一次读取512个字节,中括号内的数字自定义但最好是2的次方
            while((len=in.read(b))!=-1){
                out1.write(b,0,len);        //最好不要偷懒直接out1.write(b),这样容易出问题
            }


        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        } finally {
            try {
                if (in != null) in.close(); //及时判断关闭流,并且最好在finally语句块中关闭
                if (out != null) out.close();
                if (out1 != null) out1.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值