字节流的处理细节

来源:互联网 发布:数据库课程设计报告 编辑:程序博客网 时间:2024/06/06 05:16

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

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 0
原创粉丝点击