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.

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();

}

This gives a result of:

Text length: 1054631, Total time: 9

Text length: 1034099, Total time: 22

So, why do people use readers instead of streams?

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?

解决方案

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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值