2021-03-29

java关于IO流读取性能测试

关于io及其原理百度,这里直接上测试代码。

博主最常用的三种方式分别是:InputStreamReader、Scanner和LineIterator,下面看测试demo。


    public static void main(String[] args) throws IOException {
        long start1 = System.currentTimeMillis();
        StringBuffer sb = null;
        try(InputStreamReader reader = new InputStreamReader(
                new FileInputStream("C:\\Users\\lenovo\\Desktop\\新建文本文档.txt"), StandardCharsets.UTF_8);){
            sb = new StringBuffer();
            String lineText;
            BufferedReader bufferedReader = new BufferedReader(reader);
            while ((lineText = bufferedReader.readLine()) != null){
                sb.append(lineText).append("\n");
            }
        }catch (Exception e){
            System.out.println("读取失败");
        }
        System.out.println("BufferedReader读取完成,耗时" + (System.currentTimeMillis() - start1));
        // try(OutputStreamWriter writer = new OutputStreamWriter(
        //         new FileOutputStream("C:\\Users\\lenovo\\Desktop\\新建文本文档555.txt"), StandardCharsets.UTF_8);){
        //     BufferedWriter out = new BufferedWriter(writer);
        //     out.write(String.valueOf(sb));
        //     out.flush();
        // }catch (Exception e){
        //     System.out.println("写入失败");
        // }

        long start2 = System.currentTimeMillis();
        Scanner sc;
        StringBuffer sb2 = new StringBuffer();
        try(FileInputStream inputStream = new FileInputStream("C:\\Users\\lenovo\\Desktop\\新建文本文档.txt");) {
            sc = new Scanner(inputStream, "UTF-8");
            while (sc.hasNextLine()) {
                sb2.append(sc.nextLine()).append("\n");
            }
            System.out.println("Scanner读取完成,耗时" + (System.currentTimeMillis() - start2));
            if (sc.ioException() != null) {
                throw sc.ioException();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        long start3 = System.currentTimeMillis();
        LineIterator it = FileUtils.lineIterator(new File("C:\\Users\\lenovo\\Desktop\\新建文本文档.txt"), "UTF-8");
        StringBuffer sb3 = new StringBuffer();
        try {
            while (it.hasNext()) {
                sb3.append(it.nextLine()).append("\n");
            }
            System.out.println("LineIterator读取完成,耗时" + (System.currentTimeMillis() - start3));
        } finally {
            LineIterator.closeQuietly(it);
        }
    }

测试结果:
测试文件大小为11.6M

BufferedReader读取完成,耗时136ms
Scanner读取完成,耗时2414ms
LineIterator读取完成,耗时118ms

正常工作建议使用BufferedReader或者LineIterator就可以满足,由于scanner是将读取内容放在内存中,所以读取较大的文件时不建议使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值