0

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

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
// ...
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • This also sounds very plausible! – demaniak Jan 23 '13 at 08:12
  • @Andreas: Thanks for the reply. Its working for me. However, one thing I would like to update in this. For the very first time I ran the code it stalled and I had to forcibly stop the execution. After that when I re-ran the code it worked. I again ran it then also its working. So, the concern is as I have to use this logic in an application how can I assure myself that it runs every time its invoked. – Shashank Pandey Jan 23 '13 at 09:02
  • You would need to add some kind of monitoring to make sure that the command completes within a specific time frame, and otherwise terminate and re-execute the command. You can add this to your code (for example by implementing a Watchdog thread), but if possible I would take a look at the Apache Commons Exec project mentioned by @demaniak which provides such monitoring out-of-the-box. – Andreas Fester Jan 23 '13 at 09:09
2

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.

demaniak
  • 3,716
  • 1
  • 29
  • 34