Files.newInputStream creates a slow InputStream

On my Windows 7 Files.newInputStream returns sun.nio.ch.ChannelInputStream. When I tested its performance and FileInputStream, I was surprised to learn that FileInputStream is faster.

This test

InputStream in = new FileInputStream("test"); long t0 = System.currentTimeMillis(); byte[] a = new byte[16 * 1024]; for (int n; (n = in.read(a)) != -1;) { } System.out.println(System.currentTimeMillis() - t0); 

reads a 100 megabyte file in 125 ms. If I replace the first line with

 InputStream in = Files.newInputStream(Paths.get("test")); 

I get 320 ms.

If Files.newInputStream is slower, what advantages does it have over FileInputStream?

+6
source share
3 answers

If you tested new FileInputStream second, you probably just see the caching effect using the operating system. It is not plausible that Java causes a significant difference in the I / O binding process. Try it the other way around, and on a much larger dataset.

+8
source

I don't want to be buzzkill, but javadoc gives no benefits, and no documentation I could find

Opens a file, returning an input stream to read from the file. The stream is not buffered , and no sign or reset is required. A thread will be safe to access multiple parallel threads. Reading begins at the beginning of the file. Whether the returned stream is asynchronously closed and / or the Interrupt is highly dependent on the file system provider, and therefore not defined.

I think this method is just a utility method, which does not necessarily mean replacing or improving with FileInputStream . Note that the concurrency point may slow down a little.

+2
source

The document says

"Stream is not buffered"

This is because Files.newInputStream (Paths) supports non-blocking IO.

You can try in debug mode, you can open a non-blocking input stream and at the same time change the file, but if you use FileInputStream, you cannot do such things.

FileInputStream will require a "write lock" file, so it can accumulate the contents of the file, increase read speed.

But ChannelInputStream cannot. It must ensure that it reads the "current" contents of the file.

Above my experience, I did not check every point in the Java document.

-2
source

Source: https://habr.com/ru/post/959075/


All Articles