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?
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 (ie 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.
In what context are you executing? Are there concurrent thread using the same file?
If this is your case, FileChannel lock all or part of file that is using. The lock method (partial file or all file) depends of the plataform, and it is posible that windows 2003 has been obsolete plataform for this technics.
Solution: Change OS or use apache commons IO.
Note: If you block the file in one request and you do not unblock, you must restart jvm.
链接地址: http://www.djcxy.com/p/55622.html上一篇: 斯卡拉泛型和数值含义
下一篇: Java NIO和Windows磁盘访问