Access Java NIO and Windows Disk

Does Java NIO require special permissions for Windows?

When I run the following Java code on Windows Server 2003, it fails with a "denied access" error (which is 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 suppose 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 working on Java 5 with an administrator account. Is there any special permission for the file that needs to be installed?

+7
source share
2 answers

The reasons are indicated in the code:

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

The code is incorrect at several levels.

  • The lack of closing streams, an exception means that the file is most likely not writable. Provided that the user can actually access the โ€œexcluded accessโ€ to the type of exception for resource leaks (ie Do not close), which prevents the completion of any other operation.

  • You cannot pass the same 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 is similar, except that it can use the DMA displayed by the OS.

  • TransferTo / From is useless for windows, since the OS does not support it, so the reason it really works is that it is emulated. On Linux / Solaris / MacOS, it can just transfer X bytes and do it.

+4
source

In what context are you performing? Is there a parallel thread using the same file?

If this is your case, FileChannel blocks all or part of the used file. The locking method (partial file or the entire file) depends on plataform, and it is possible that Windows 2003 was an outdated motherboard for this technique.

Solution: change OS or use apache commons IO.

Note. If you lock the file in one request and do not unlock it, you must restart jvm.

0
source

All Articles