Monday, September 20, 2010

Java method to copy file to UNC network location

Small update on something I used for work. I needed a way to copy a file stored locally from one machine to another machine on the network with a shared folder. This is an all Windows environment.

To copy a file with Java (JRE 1.4 or higher) the method found here was really helpful:

...
//File in = new File("local-file.txt")
//File out = new File("\\\\network\folder\file.txt")
FileChannel inChannel = new
FileInputStream(in).getChannel();
FileChannel outChannel = new
FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
...

Credit: http://www.rgagnon.com/javadetails/java-0064.html

Used the "new" technique using the java.nio package for transferring the file. See FileChannel.transferTo()

The example in the how-to page describes copying an input File in to an output File out

All I had to do was make sure that Java would understand a UNC style network file path for the out File that I wanted to copy to. It was really as simple as that, and worked perfectly. Just remember to double-escape the "\" including the starting "\\" prefix in your UNC file path.

File out = new File("\\\\host-name\\path\\to\\target-file.zip");

That page also discusses an issue on Windows where files of sizes greater than 64 MB fail with an "java.io.IOException: Insufficient system resources exist to complete the requested service" error. I initially tried with the suggested workaround to transfer the file in 64 MB chunks, which worked. For the record the file transfer for a larger file (167 MB) took around 18sec with this method. Given that this issue is several years and java versions old I thought I would try this out without splitting up the file.

My development system is Windows 7, JRE 1.5.0_22, the target host with the network share was on Windows XP. Using the original transferTo method without splitting the file successfully copied my large test file with no errors. There was also a slight performance gain as the copy took about 16 seconds that time.

Doing a little research in the Oracle Sun Developer Network Bug Database, it seems this may have been an issue fixed in: 6431344. Or it may have been that this was an OS problem and doesn't manifest on the Win 7 platform. In either case seems to be working.

Related bugs:
6822107
6486606

No comments:

Post a Comment