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.