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?
Asked
Active
Viewed 3.7k times
14
-
If this is for 'users', consider picking a letter towards the end of the alphabet that won't get made unavailable by having one or two usb devices plugged in. – Cheekysoft Oct 16 '08 at 15:49
-
Thats good advice. USB devices take the first available. In our case, the letter of choice is out of our control. We just need to get it mapped. – Brett McCann Oct 16 '08 at 19:37
3 Answers
16
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}]

Jorge Ferreira
- 96,051
- 25
- 122
- 132
-
What happens if the user has already mapped f:? What happens if we run the same program a couple of times and kill it in the middle (e.g. during debugging session)? – ddimitrov Oct 16 '08 at 14:57
-
If the user has already mapped drive f: you would get the "System error 85 has occurred." in the process output. You can just scan for it. – Jorge Ferreira Oct 16 '08 at 15:02
-
After the mounting, we can perform operations on the directory using normal FS commands right? Can you add an example to read a file? When I do `Path share = Paths.get(new URI("f:\"));` i get an error Provider "f" not installed. – Shubham Jan 11 '21 at 14:41
-
11
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.

ddimitrov
- 3,293
- 3
- 31
- 46
5
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) {
}

Jonas K
- 4,215
- 2
- 24
- 25
-
Directly using net.exe does not handle error cases and is not platform neutral. – munsingh May 11 '15 at 09:19
-
1