Java IO:逐行写入文本文件 [英] Java IO : Writing into a text file line by line

查看:645
本文介绍了Java IO:逐行写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需求,我需要逐行写一个文本文件。
行数可能高达80K。我打开文件输出流,并在一个for循环,迭代列表,并形成一行,并写入文件行。

这意味着80K写操作是在文件上做的。

<>打开和写入文件非常频繁地妨碍了性能。
任何人都可以建议一个最好的方式哟解决这个需求在Java IO?

谢谢。

解决方案

你还没有发布任何代码,但只要你的写入缓冲,你几乎不应该注意到性能。使用 BufferedWriter.write(),然后加上 BufferedWriter.newLine(),,尽量避免冲洗。不要排队,只要写下你要写的任何内容即可。如果不是所有的开销,你可能实际上是字符串连接,而不是I / O。

在其他答案中提到的替代方案要么实现在更巴洛克式方式,或涉及NIO这是不会更快。

I have a requirement where i need to write a text file line by line. The number of lines may be up to 80K . I am opening the file output stream and inside a for-loop , iterating a list and forming a line and writing the line into the file.

This means 80K write operations are made on the file .

Opening and writing the file very frequently hinders performance. Can anyone suggest a best way yo address this requirement in Java IO?

Thanks.

解决方案

You haven't posted any code, but as long as your writes are buffered you should hardly notice the performance. Use BufferedWriter.write() followed by BufferedWriter.newLine(), and avoid flushing as much as you can. Don't 'form a line', just write whatever you have to write as soon as you have it. Much if not all of the overhead you are observing may actually be string concatenation rather than I/O.

The alternatives mentioned in other answers either amount to this implemented in more baroque ways, or involve NIO which isn't going to be any faster.

这篇关于Java IO:逐行写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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