Java文件的几种读取、输出方式

1、字节流----对文件读取(速度慢)

   /**
     * 字节流---文件的读取,输出(缺点:速度慢)
     * 
     * @throws Exception
     */
    @Test
    public void testIO1() throws Exception {
        // 输入字节流对象
        InputStream in = new FileInputStream("pkg/a.txt");
        // 输出字节流对象
        OutputStream out = new FileOutputStream("pkg/b.txt");
        //这里定义个字节数组,用来指定每次读取的字节数
        byte[] b = new byte[1024];
        int len = -1;
        while ((len = in.read(b, 0, b.length)) != -1) {
            String str = new String(b, 0, len, "UTF-8");
            System.out.println(str);
            out.write(b, 0, len);
        }
        //关闭对象
        out.close();
        in.close();
    }

2、带缓存的字节流---文件读取(速度快)

   /**
     * 缓存字节流---文件读取,输出(推荐:速度快)
     * 
     * @throws Exception
     */
    @Test
    public void testIO2() throws Exception {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("pkg/a.txt"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("pkg/b.txt"));

        byte[] b = new byte[1024];
        int len = -1;
        while ((len = in.read(b, 0, b.length)) != -1) {
            String str = new String(b, 0, len, "UTF-8");
            System.out.println(str);
            out.write(b, 0, len);
        }
        //刷新缓冲
        out.flush();
        //关闭流对象
        in.close();
        out.close();
    }

3、字节流reader,这个方法不能指定读取的字节数(不推荐)

    /*
     * 字节流reader,不能指定字节长度读取,不建议使用
     */
    @Test
    public void testIO3() throws Exception {
        InputStreamReader in = new InputStreamReader(new FileInputStream("pkg/a.txt"), "UTF-8");
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("pkg/b.txt"));

        int len = -1;
        while ((len = in.read()) != -1) {
            System.out.println(len);
            // 写入文件
            out.write(len);
        }
        out.flush();
        in.close();
        out.close();
    }

4、带缓冲的字节流读取方式,readLine()

   /**
     * 另一种字节流读取方式----可以提供readLine()的方法,一次读取一行。
     * 
     * @throws Exception
     */
    @Test
    public void testIO4() throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("pkg/a.txt"), "UTF-8"));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("pkg/b.txt"), "UTF-8"));
        String str;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
            out.write(str + "\n");
        }
        out.flush();
        in.close();
        out.close();
    }

小结:实际在用的过程,肯定是选择带有缓冲区的字节流读取方式,另外能够指定每次读取的字节数最好不过了。因此,方式2 推荐使用。


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值