Executing a net use command

送分小仙女□ 提交于 2019-12-13 02:57:22

问题


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
// ...


来源:https://stackoverflow.com/questions/14474747/executing-a-net-use-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!