Write a file to a remote location using Java with network path or drive?

ohseekay picture ohseekay · Aug 15, 2013 · Viewed 36.1k times · Source

I have shared a folder on my server using Windows sharing. On another computer, where I am running my code on, I have mapped a network drive pointing to that folder.

In my code, I transfer files from my local computer to my server every now and then. Something like this:

File srcFile = new File("C:\\test.mpg");
File destFile = new File(...);

// error checking
FileUtils.moveFile(srcFile, destFile);

For destFile, which approach should I use? My current approach:

File destFile = new File("Z:\\folder\\test.mpg");

or using a network path:

File destFile = new File("\\192.168.123.123\\folder\\test.mpg");

I ask this because recently I have encountered cases where the file transfer fails because my program is unable to write to my network drive because it is not logged on, and I have to manually go to the drive and enter my credentials and enable "Stay connected" option.

Answer

You can use mapped drives or full network paths equivalently; Java doesn't care and just passes the file name on to the OS. Note that if you're using a network path, you need \\\\ at the beginning.