Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 908
ohseekay Avatar asked Aug 15 '13 03:08

ohseekay


2 Answers

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.

like image 81
chrylis -cautiouslyoptimistic- Avatar answered Sep 19 '22 17:09

chrylis -cautiouslyoptimistic-


You can use the JCIFS library to access a Windows SMB share in Java. Using it, you could do something like the following:

String smbUrl = "smb://username:password@server/share/file";
SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL));
like image 43
Ahsan Shah Avatar answered Sep 21 '22 17:09

Ahsan Shah