Executing a net use command

2019-09-12 12:05发布

问题:

I need to execute a net use command which is written in a batch file to enable a drive. Batch file is as follows:

net use * /delete /Y
net use l: \\<windows drive name> /user:<domain>\<username> <password>

The above batch file enables a drive for me and its visible as L: drive to me. I need to execute this batch file through java code and then write the some files onto this drive.

I am using the below code to execute this batch file:

String[] array = { "cmd", "/C", "start", "C:/file.bat" };
Runtime.getRuntime().exec(array);

Problem is when I try to access the drive to write the files it gives me a path not found exception. Sometimes it runs and sometimes it doesn't.

Friends can anyone help me to understand where is the issue. What wrong step I am performing. In case I am not clear with my question do let me know.

回答1:

I suspect when that hits the actual command shell, windows does not like the "/". Maybe try "\" instead? External process execution is a bit tricky - you might want to look at Apache Commons Exec project to help you out there.



回答2:

Sometimes it runs and sometimes it doesn't.

This looks like a race condition. Runtime.exec() executes your command in a separate process, while the calling application continues to run. It is then undefined whether the batch file has already completed or not when you try to access the file.

Runtime.exec() returns a Process object, which you can use to communicate with the sub process. In your case, it should be sufficient to wait for the process to complete:

Process p = Runtime.getRuntime().exec(array);
p.waitFor();

// Now, your batch file should be completed and you can continue
// ...