Java - 从文件中读取。输入流与读者 [英] Java -- reading from a file. Input stream vs. reader

查看:154
本文介绍了Java - 从文件中读取。输入流与读者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看到的从文件中读取的每个Java实现中,我几乎总是看到用于逐行读取的文件读取器。我的想法是,这会非常低效,因为它需要每行系统调用。

In every Java implementation I see of reading from a file, I almost always see a file reader used to read line by line. My thought would be that this would be terribly inefficient because it requires a system call per line.

我一直在做的是使用输入流并抓住字节直接。在我的实验中,这明显更快。我的测试是一个1MB的文件。

What I'd been doing instead is to use an input stream and grab the bytes directly. In my experiments, this is significantly faster. My test was a 1MB file.

    //Stream method
    try {
        Long startTime = new Date().getTime();

        InputStream is = new FileInputStream("test");
        byte[] b = new byte[is.available()];
        is.read(b);
        String text = new String(b);
        //System.out.println(text);

        Long endTime = new Date().getTime();
        System.out.println("Text length: " + text.length() + ", Total time: " + (endTime - startTime));

    }
    catch (Exception e) {
        e.printStackTrace();
    }

    //Reader method
    try {
        Long startTime = new Date().getTime();

        BufferedReader br = new BufferedReader(new FileReader("test"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        String text = sb.toString();

        Long endTime = new Date().getTime();
        System.out.println("Text length: " + text.length() + ", Total time: " + (endTime - startTime));

    }
    catch (Exception e) {
        e.printStackTrace();
    }

结果如下:

Text length: 1054631, Total time: 9
Text length: 1034099, Total time: 22

那么,为什么人们使用读者代替流?

So, why do people use readers instead of streams?

如果我有一个带文本的方法file并返回一个包含所有文本的String,是否最好使用流来完成?

If I have a method that takes a text file and returns a String that contains all of the text, is it necessarily better to do it using a stream?

推荐答案

你是比较苹果和香蕉。即使使用bufferedReader,一次读取一行也会降低效率,而不是尽可能快地抓取数据。请注意,不鼓励使用可用,因为它在所有情况下都不准确。当我开始使用密码流时,我自己发现了这一点。

You are comparing apples to bananas. Reading one line at a time is going to be less efficient even with a bufferedReader than grabbing data as fast as possible. Note that use of available is discouraged, as it is not accurate in all situations. I found this out myself when I started using cipher streams.

这篇关于Java - 从文件中读取。输入流与读者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆