We are working with some legacy code that accesses a shared drive by the letter (f:\ for example). Using the UNC notation is not an option. Our Java wrapper app will run as a service, and as the first step, I would like to map the drive explicitly in the code. Has anyone done this?
I think the easiest way is to use the Runtime.getRuntime().exec() method and call the "net use" command.
For example:
try {
// Execute a command without arguments
String command = "C:\\Windows\\system32\\net.exe use F: \\\\server\\share /user:user password";
Process child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}
Consider executing the DOS command that maps a network drive as in the following code:
String command = "c:\\windows\\system32\\net.exe use f: \\\\machine\\share /user:user password";
Process p = Runtime.getRuntime().exec(command);
...
See details on net use command:
The syntax of this command is: NET USE [devicename | *] [\\computername\sharename[\volume] [password | *]] [/USER:[domainname\]username] [/USER:[dotted domain name\]username] [/USER:[username@dotted domain name] [/SMARTCARD] [/SAVECRED] [[/DELETE] | [/PERSISTENT:{YES | NO}]] NET USE {devicename | *} [password | *] /HOME NET USE [/PERSISTENT:{YES | NO}]
You can use JCIFS
http://jcifs.samba.org/src/docs/api/jcifs/smb/SmbFile.html
or if you want higher level API and support for other protocols like FTP, Zip and others:
http://commons.apache.org/vfs/filesystems.html
Both options are pure Java and cross platform.
@ smink , Jonas Klemming
Will this approach work in case java application is run as windows Service.
When I tried running this as standalone java App.I got my drive mounted (Though it's different thing I can not access any of the files using FILE IO. it is simple not accessible)
But in case of java app is run as windows service, same code failed to mount network drive with an error
System error 1312 has occurred.A specified logon session does not exist. It may already have been terminated.
Do you have any idea about this
The posted code chunk worked for me, with some issues. Thank you for it.
The problem is when I tried to map the drive and call a method/function in one go, to access the files, it gave file/path not found exception. I guess the java.IO.File tried to access the path prior to completion of the drive mapping. But if I used the java.IO.File in next time it worked as the drive was now mapped. Is there any way to get any acknowledgement or make our thread wait untill the Process is executed successfully? How to get/capture error message generated by commands excuted with above code?
I also need to delete the mapped drive from Java and tried as
String commandDelete = "c:\windows\system32\net.exe use Z: /delete"; Process p2 = Runtime.getRuntime().exec(commandDelete); However it is giving random behavior. May be as above.
How to fetch the mapped drives with Java?