Execute .bat file from java and wait till its finished - java

I have gone through few questions raised on how to achieve this.
I used process.waitFor() and /wait as mentioned here. The problem is by doing so it waits not just till the command is executed but until cmd prompt is closed (can be done by adding exit in the bat file). But I cannot modify bat file as its a Product file.
Runtime run = Runtime.getRuntime();
try {
String path = "C:/Folder/c.bat";
String executeCmd= "cmd /c start /wait "+path;
final Process process =run.exec(executeCmd);
process.waitFor();
System.out.println("did I wait?");
} catch (Exception e) {
e.printStackTrace();
}
How to make it wait only till the command is executed.

You can create a helper batch file with following content:
start /wait %1\c.bat
exit
Store this helper batch anywhere you want to.
Then start this helper batch file with the path to c.bat as its parameter.
Runtime run = Runtime.getRuntime();
try {
String pathToCBatch = "C:\\Folder\\";
String pathToHelperBatch = "c:/helperBatch.bat";
String executeCmd = "cmd /c start /wait " + pathToHelperBatch + " " + pathToCBatch;
final Process process = run.exec(executeCmd);
System.out.println(System.currentTimeMillis());
process.waitFor();
System.out.println(System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}

I have also the same issue: "call a Batch file and wait until it's finished" (Windows PC). This solution works for me :
StringBuilder command = new StringBuilder("cmd /c start /wait C:\\script.bat");
// my script take 2 file as arguments
command.append(" ").append(inputFile);
command.append(" ").append(outputFile);
try {
final Process p = Runtime.getRuntime().exec(command.toString());
p.waitFor();
} catch (InterruptedException e) {
System.out.println(e);
}

also if the directory has space in it then the command wont work from string of arrey
so instead do this
File file = new File("E:\\NetBeans Projects\\Test.bat");
String[] command = {"cmd.exe", "/c", "start", file.getName() };
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command , null , file.getParentFile());

dont work for me to exit cmd from java
i have come with a solution
i added "exit" in my .bat file at the end and it works now
example :
this is my "adservice.google.com.bat" bat file which dont exit after executing from java
netsh advfirewall firewall add rule name="adservice.google.com.bat" protocol=any dir=out action=block remoteip=2404:6800:4009:80f::2002,216.58.203.34
so i have to add "exit" in it , in the last line
netsh advfirewall firewall add rule name="adservice.google.com.bat" protocol=any dir=out action=block remoteip=2404:6800:4009:80f::2002,216.58.203.34
exit

Related

Going into a directory from Windows command prompt via Java

Having a little bit of trouble with getting some commands to run in Windows command prompt via Java. I am looking to go into my system32 folder and run a certain file however it does not populate the command. Segment of the code below:
System.out.print("Press 1 for Normal or 2 for Keygen - " + client);
String mode = input.nextLine().trim();
if (mode.equals("1")) {
String command = "cmd /c start cmd.exe";
final String dosCommand = "cmd /c dir /s";
final String location = "C:\\WINDOWS\\system32";
Process child = Runtime.getRuntime().exec(command);
OutputStream out = child.getOutputStream();
out.write(dosCommand.getBytes());
out.flush();
out.write(location.getBytes());
out.close();
} else if (mode.equals("2")) {
} else {
System.out.println("Option not recognised");
}
You seem to be getting bogged down in your code. Try using this instead:
System.out.print("Press 1 for Normal or 2 for Keygen - " + client);
String mode = input.nextLine().trim();
if (mode.equals("1")) {
final String location = "C:\\WINDOWS\\system32";
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start dir /p", null, new File(location));
} else if (mode.equals("2")) {
} else {
System.out.println("Option not recognised");
}
Here is what happened when I ran this code snippet on my own computer:
If you want to run an actual program, you can just specify this inside the call to Runtime.exec(). For example, suppose you want to launch a window and print out the Java version. The command for this is java -version and you can use this line of code:
rt.exec("cmd.exe /c start cmd /k java -version", null, new File(loc));
Here, you will notice that I added an extra cmd /k to the command. This will keep the window open even after the program has finished running.

How to handle spaces in path to a windows batch file?

I have a batch file on windows machine.
The path to the same is having spaces in it. E.g. C:\Hello World\MyFile.bat
I am trying to execute the batch file through java as:
Runtime.getRuntime().exec(dosCommand + destinationFilePath + batch)
But, as the path has spaces, it says "C:\Hello" is not a valid command or directory.
I tried this too:
Complete command: cmd /c start /wait "C:/Hello World/MyFile.bat" It opens the command prompt, but does not go to the folder Hello World and does not execute the bat file
How do I handle this situation.
Let me know if any additional Info. is required.
Using quotation marks ("C:\Hello World\MyFile.bat") should do the trick. Within Java you'll have to secape the quotation marks with \ (String batch = "\"C:\Hello World\MyFile.bat\"").
I was able to solve it using ProcessBuilder.
The directory in which the bat file is present can be added to the working directory as:
processBuilder.directory(new File("C:\hello world\"));
This works like gem.
int result = 1;
final File batchFile = new File("C:\\hello world\\MyFile.bat");
final File outputFile = new File(String.format("C:\\hello world\\output_%tY%<tm%<td_%<tH%<tM%<tS.txt", System.currentTimeMillis()));
final ProcessBuilder processBuilder = new ProcessBuilder(batchFile.getAbsolutePath());
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(outputFile);
processBuilder.directory(new File("C:\\hello world\\"));
try {
final Process process = processBuilder.start();
if (process.waitFor() == 0) {
result = 0;
}
System.out.println("Processed finished with status: " + result);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Did you try to escape quotes surrounding the path such as :
Runtime.getRuntime().exec(dosCommand + "\"" + destinationFilePath + batch + "\"")
I just solved this problem using a ProcessBuilder as well, however I gave the directory with a space to processBuilder.directory and ran the command with the bat file name.
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start", "/wait", "export.bat");
pb.directory(new File(batDirectoryWithSpace));
pb.redirectError();
try {
Process process = pb.start();
System.out.println("Exited with " + process.waitFor());
}
catch (IOException | InterruptedException ex) {
Exceptions.printStackTrace(ex);
}

Runtime.getRuntime().exec could not execute/show Tabtip.exe

I've set this OnClick method in JavaFX SceneBuilder on a text field that will pop up the Windows 8 touch keyboard if the user select the textfield. However it seems to be nothing happen when I click on the textfield but when I try to check Tabtip.exe in the task manager, it did shown up there. The codes are:
try
{
Runtime rt = Runtime.getRtuntime();
rt.exec( "cmd /c C:\\Programs Files\\Common Files\\Microsoft Shared\\ink\\TabTip.exe");
}
catch
{
ex.printStackTrace();
}
There is not errors triggered or whatsoever, and TabTip.exe is running in task manager, but the pop up keyboard does not show up, anyone has any solution to this? Thanks!
Whenever you want to execute a command which contains spaces in command prompt, you have to wrap it in double quotes.
Like this:
String commandStr = "cmd /c \"C:\\Program Files\\Common Files\\Microsoft Shared\\ink\\mip.exe\"";
rt.exec( commandStr );
And In addition to that, if you want to know your errors, you can get error stream from object of class Process which is returned by runtimeObject.exec().
String commandStr = "cmd /c C:\\Programs Files\\Common Files\\Microsoft Shared\\ink\\TabTip.exe"; // Like you did
InputStream is = rt.exec( commandStr ).getErrorStream();
int b;
while((b=(is.read()))!=-1)
System.out.print((char)b);
}
Please do like this. For me it is ok in window10 with javaFx application.
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "\"C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe");
builder.redirectErrorStream(true);
Process p;
try
{
p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true)
{
line = r.readLine();
if (line == null)
{
break;
}
System.out.println(line);
}
}
catch (IOException e)`enter code here`
{
// TODO Auto-generated catch block
e.printStackTrace();
}`enter code here`
The only way to run the TabTip.exe is to run the software on Admin mode.
I found the following batch code on the internet.
How to Use On-Screen and Touch Keyboard Instead of Spiral Keyboard
tasklist | find /I "TabTip.exe" >NUL && (taskkill /IM "TabTip.exe" /T)
start "" "TabTip.exe"
That code kills the TabTip process and executes a new TabTip.
In my case, I created a file called keyboard.bat and added the previous example.
In java, I created a method in order to read this file in the same folder.
That is my code
try{
File file = new File("keyboard.bat");
Runtime.getRuntime().exec(file.getAbsolutePath());
}catch(IOException ex){
Logger.getLogger(RunGazePoint.class.getName()).log(Level.SEVERE, null, ex);
}
after that, I compile my app and wrap it in executable mode with launch4j software.
Another way Is to execute by command, If you are using a multithreaded the system can avoid the lecture of file and not execute the software.
create two methods in order to kill and call the keyboard.
//hide the Keyboard
String[] array = new String[]{"cmd.exe","/c","taskkill /IM \"TabTip.exe\" /F\n" +
""};
Runtime.getRuntime().exec(array);
//Show the keyboard
String[] array = new String[]{"cmd.exe","/c","start \"\" \"TabTip.exe\""};
Runtime.getRuntime().exec(array);

Running csstidy from Java

I am trying to develop a Java tool to refactor css files. I am trying to access the command prompt from Java. The command prompt is opening fine but it's not running the csstidy exe file.
try {
String command = "cmd /c start cmd.exe /K \"cd C:/Users/BS11040/Desktop/CSSTIDY_JAVA/";
Process child = Runtime.getRuntime().exec(command);
OutputStream out = child.getOutputStream();
out.write("csstidy.exe /r/n".getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Try invoking your .exe directly, you are doing it way to complicated:
String command = "C:/Users/BS11040/Desktop/CSSTIDY_JAVA/csstidy.exe";
Process child = Runtime.getRuntime().exec(command);
And by the way, the codes for CR and NEWLINE are \n and \r , take care to use the right slash!

Executing a Command from Java and Waiting for the Command to Finish

In my Java program, I create a process that executes a command to run a batch file like this:
try {
File tempFile = new File("C:/Users/Public/temp.cmd");
tempFile.createNewFile();
tempFile.deleteOnExit();
setContents(tempFile, recipe.getText()); //Writes some user input to file
String cmd = "cmd /c start " + tempFile.getPath();
Process p = Runtime.getRuntime().exec(cmd);
int exitVal = p.waitFor();
refreshActionPerformed(evt);
} catch (InterruptedException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Now, what I would like to have happen is that the command
refreshActionPerformed(evt);
runs only after the batch file I called has finished executing. But right now, it runs immediately after the Command Prompt opens.
How do I fix this?
I manged to find the answer elsewhere. To keep the initial process open until the batch file finished all you need is "/wait"
Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat");
int exitVal = p.waitFor();
calling "cmd /c start" causes cmd to fire off another instance and exit immediately. Try taking out the "start" command.
The answer given is correct. I added that the window opened by the code needs to be closed manually.
Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat");
int exitVal = p.waitFor();

Categories