I am trying to execute .bat file using java process builder but it does not starts the process. Please tell me what i am doing wrong here. This code works fine with linux envoirnment when I replace file.bat with ./file.sh
final ArrayList<String> command = new ArrayList<String>();
command.add(WORKING_DIR+File.separator+"file.bat");
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.redirectErrorStream(true);
builder.start();
} catch (IOException e) {
logger.error("Could not start process." ,e);
}
First element in array must be an executable. So you have to invoke cmd.exe in order to call you batch file.
ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", WORKING_DIR + File.separator + "file.bat"}));
Make sure the path to the bat file is correct. You can either debug it using a debugger or put a sysout to determine that:
final ArrayList<String> command = new ArrayList<String>();
System.out.println("Batch file path : " + WORKING_DIR+File.separator+"file.bat")
command.add(WORKING_DIR+File.separator+"file.bat");
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.redirectErrorStream(true);
builder.start();
} catch (IOException e) {
logger.error("Could not start process." ,e);
}
Related
I'm starting a Java process in my Java code. I have coded a function to close this process. But the process doesn't get terminated.
Here is my code for create the process:
Process process = null;
final ProcessBuilder builder = new ProcessBuilder("java", "-jar", "-Xmx512M", "server.jar");
builder.directory(new File("temp/"+serverName+"/"));
try {
process = builder.start();
} catch (IOException e) {
e.printStackTrace();
}
Launcher.serverProcess.put(serverName, process);
from another class I would like to stop the server:
Process temp = Launcher.serverProcess.get(serverName);
while(temp.isAlive()) {
temp.destroy();
temp.destroyForcibly();
}
Launcher.serverProcess.remove(serverName);
After entering the command to stop the process, I want to remove the directory. Whenever I try this I am only told that the folder is being used and I cannot delete it. With taskkill / F / IM java.exe I stop the process and can then delete the folder
In an application I am writing, I need to use the javaagent option to call an external jar in the same folder as my current jar file. When I run the code from the jar file, I get told: "Error: Could not find or load main class -javaagent:" but when I am running it from a batch file, it works as excepted.
I am using a ProcessBuilder to start the application:
String java = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar +"java.exe";
File transagent = new File(pluginDir + File.separatorChar + "TransAgent.jar");
String doublequote = String.valueOf('"');
List<String> commandlist = new ArrayList<String>();
commandlist.add(java);
commandlist.add(" -javaagent:");
commandlist.add(doublequote);
commandlist.add(transagent.getAbsolutePath());
commandlist.add(doublequote);
for(int i = 0; i < commandlist.size(); i++){
String part = commandlist.get(i);
System.out.print(part);
}
System.out.println();
ProcessBuilder pb = new ProcessBuilder();
pb.command(commandlist);
pb.redirectError(Redirect.appendTo(errorfile));
pb.redirectOutput(Redirect.appendTo(logfile));
try {
pb.start();
} catch (IOException e) {
e.printStackTrace();
}
But, when I go to the error file, I see "Error: Could not find or load main class -javaagent:"
This would usually be thrown if the option isn't valid, but I've checked the dash to work file. And I put what printed from the application in a batch file, and it worked fine. Why?
You can try this code below:
ProcessBuilder pb = new ProcessBuilder("java", "-javaagent:"+transagent.getAbsolutePath(), "YouMainClass");
pb.redirectError(Redirect.appendTo(errorfile));
pb.redirectOutput(Redirect.appendTo(logfile));
try
{
pb.start();
}
catch(IOException e)
{
e.printStackTrace();
}
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);
}
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
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);