Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO and Windows disk access

Does Java NIO need special permissions on Windows?

When I run the following Java code on Windows Server 2003, it fails with an "access denied" error (that's the whole message in the cygwin terminal window):

new FileOutputStream(outputFile).getChannel()
  .transferFrom(new FileInputStream(inputFile).getChannel(), 0, Long.MAX_VALUE);

but if I use Apache commons-io (which I assume does NOT use NIO, it works with the same input and output files:

final FileInputStream inputStream = new FileInputStream(inputFile)
final FileOutputStream outputStream = new FileOutputStream(outputStream)
IOUtils.copy(inputStream, outputStream);

I am running in Java 5 with an administrator account. Is there some special file permission that must set?

like image 334
Ralph Avatar asked Oct 14 '11 12:10

Ralph


1 Answers

The reasons is in the code:

new FileOutputStream(outputFile).getChannel() .transferFrom(new FileInputStream(inputFile).getChannel(), 0, Long.MAX_VALUE);

The code is wrong on few levels.

  • no closing of the streams, the exception means most likely the file is unavailable for writing. Provided the user can actually access, "denied access" type of exception point to resource leaks (i.e. not closing) which prevents any other operation to finish.

  • You can't transfer like that w/o loop. Although it will work on Windows, transferTo/From does not read/write everything at once. Consider it the same as inputStream.read()->outputStream.write(), it's similar except it can use DMA mapped by the OS.

  • TransferTo/From is useless on windows as the OS does not support it, hence the reason it actually works: it's emulated. On Linux/Solaris/MacOS it can just transfer X bytes and be done it.

like image 180
bestsss Avatar answered Oct 05 '22 07:10

bestsss