java 文本输出,Java:将文本文件输出到控制台

I'm attempting to output a text file to the console with Java. I was wondering what is the most efficient way of doing so?

I've researched several methods however, it's difficult to discern which is the least performance impacted solution.

Outputting a text file to the console would involve reading in each line in the file, then writing it to the console.

Is it better to use:

Buffered Reader with a FileReader, reading in lines and doing a bunch of system.out.println calls?

BufferedReader in = new BufferedReader(new FileReader("C:\\logs\\"));

while (in.readLine() != null) {

System.out.println(blah blah blah);

}

in.close();

Scanner reading each line in the file and doing system.print calls?

while (scanner.hasNextLine()) {

System.out.println(blah blah blah);

}

Thanks.

解决方案

If you're not interested in the character based data the text file is containing, just stream it "raw" as bytes.

InputStream input = new BufferedInputStream(new FileInputStream("C:/logs.txt"));

byte[] buffer = new byte[8192];

try {

for (int length = 0; (length = input.read(buffer)) != -1;) {

System.out.write(buffer, 0, length);

}

} finally {

input.close();

}

This saves the cost of unnecessarily massaging between bytes and characters and also scanning and splitting on newlines and appending them once again.

As to the performance, you may find this article interesting. According the article, a FileChannel with a 256K byte array which is read through a wrapped ByteBuffer and written directly from the byte array is the fastest way.

FileInputStream input = new FileInputStream("C:/logs.txt");

FileChannel channel = input.getChannel();

byte[] buffer = new byte[256 * 1024];

ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);

try {

for (int length = 0; (length = channel.read(byteBuffer)) != -1;) {

System.out.write(buffer, 0, length);

byteBuffer.clear();

}

} finally {

input.close();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值