Question

According to the official Java Tutorial, the best way to write into a file is: http://docs.oracle.com/javase/tutorial/essential/io/file.html#channels

Before I create my own FileUtil.write(file, text) method using NIO.2, I wonder if there already is such a method somewhere.

I checked the sources of the latest apache commons io and guava but they both just create a FileOutputStream, convert the string into a byte array and write. I was surprised.

So I have 2 questions:

  1. I thought that NIO.2 is faster than FileOutputStream. But since commons io and guava don't use them I wonder if this is true. The question is: is NIO faster than FileOutputStream ?
  2. If NIO.2 is faster, is there a library that uses it?
Was it helpful?

Solution

NIO is supposed to be faster since it can work with direct buffers. From ByteBuffer API:

Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top