I want to run a .exe file from my java code,along with passing few arguments/options to the .exe file.
So basically, I did following:
BufferedReader br = null;
OutputResult out = new OutputResult();
String commandStr= "cmd.exe /C A-B/xyz.exe health -U admin -P admin";
Process p = Runtime.getRuntime().exec(commandStr);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
out.add(line.trim());
}
NOTE: Here A-B is name of the directory in which xyz.exe is located.
But when the variable out is printed, it actually shows that it has nothing.
So instead of above code I modified it to the following:
BufferedReader bre = null;
OutputResult oute = new OutputResult();
String commandStr= "cmd.exe /C A-B/xyz.exe health -U admin -P admin";
Process p = Runtime.getRuntime().exec(commandStr);
bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bre.readLine()) != null) {
oute.add(line.trim());
}
Now here when the variable oute is printed, it shows the message,
'A-B' is not recognized as an internal or external command, operable program or batch file.
So my question is that why A-B is not being treated as a directory inside which the actual .exe file resides.
Please resolve the error if any one knows about this problem.
You should use a full path to your target xyz.exe - when you execute cmd.exe like that, it's not relative to the folder of your Java program, it's relative to C:\Windows\System32 therefore it can't see your A-B folder.
So, for example:
cmd.exe /C C:/A-B/xyz.exe health -U admin -P admin
And as #CSK correctly noticed, you can execute your .exe directly, without cmd.exe. For examle:
Process process = new ProcessBuilder("C:/A-B/xyz.exe", "health", "-U", "admin", "-P", "-admin").start();
I know that, for example, Java on Raspbian can't access directories with a space (for example /New Folder). I guess its some problem about how Raspbian considers the ' ' char when creating directory. Possibly, Windows might have the same problem with the '-' char. Can you rename the directory without any such chars and try again?
(I use a Mac so I'm unable to recreate the problem. Another option can be, if this is in fact not a problem to do with chars, to create a shell script from which the exe is executed and instead run this script via Java. I am only advising this because I used this method before without any problems.)
Related
I´m running a java project using gnuplot to generate charts in pdf but I want to save those files in another folder outside my working directory. Is that possible?
I have this for now
Process proc = Runtime.getRuntime().exec("gnuplot test.gp");
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
In gnuplot console check help command line options. There is the option -e.
You need to have the following argument for exec() in Java.
"gnuplot -e myOutput='<YourPDF>' test.gp"
where you have to replace <YourPDF> with your path. Since I do not know Java, the Java-people have to tell you how you get this done.
A minimal gnuplot script would for example look like the following:
set term pdfcairo
set output myOutput
plot sin(x) # or whatever
set output
I want to run a batch file using a java program, when I double click the .bat file it asks me to enter 'D' and after that it creates some folders in C drive, below is the contents of the .bat file:
xcopy "data" "C:\data" /S
xcopy "rapid" "C:\rapid" /S
subst x: /D
subst x: C:\
My Java code is as below:
try {
//C:\Desktop\Speed\view_R36_WD_Release\RAPID\switchToLive.Bat
String cmds[] = {"C:\\Users\\608521747\\Desktop\\Speed\\view_R36_WD_Release\\RAPID\\switchToDev.bat"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmds);
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
String strLine = "";
while ((strLine = bufferedrReader.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
its not giving me any errors but it neither ask me to enter any value nor it creates any folder.
I want to know what do I need to do in java code so that it will ask me to enter the 'D' and then the .bat file should continue in a normal flow.
Any help is appreciated.
Your code needs to specify which program to execute your .bat file with.
Start narrowing down with the following fix.
p = run.exec("cmd.exe /c " + cmds);
Also try this link for similar code for similar question previously answered here.
Batch files are not executable files. So you will need to run cmd.exe and pass the batch file as parameter.
Please refer to this post - it addresses the same issue and provides a good solution - How do I run a batch file from my Java Application?.
This question already has answers here:
How do I get the directory where a Bash script is located from within the script itself?
(74 answers)
Closed 8 years ago.
I have an java application.And I use Runtime.getRuntime().exec for call a batch file.When I call a linux batch file using with Runtime.getRuntime().exec the batch file could not find its own directory.
I use pwd command in batch file but it returns application path.
I need batch file's own physical path from itself.
How can I do this?
You must use a ProcessBuilder in order to acomplish that:
ProcessBuilder builder = new ProcessBuilder( "pathToExecutable");
builder.directory( new File( "..." ).getAbsoluteFile() ); //sets process builder working directory
Try this . Its working for me.
Process p = Runtime.getRuntime().exec("pwd");
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
Batch files, if you're specifically referring to files with the '.bat' extension, are designed to be used with Microsoft's Command Prompt shell ('cmd.exe') in Windows, as they are script files containing a sequence of commands specifically for this shell, and as such will not work with Unix shells such as Bash.
Assuming you actually mean a Unix 'shell script', and not specifically a Microsoft 'batch file', you'd be better off using the ProcessBuilder class, as it provides greater flexibility than Runtime's exec() method.
To use ProcessBuilder to run a script in its own directory, set the builder's directory to the same directory that you're using to point to the script, like so:
// Point to wherever your script is stored, for example:
String script = "/home/andy/bin/myscript.sh";
String directory = new File(script).getParent();
// Point to the shell that will run the script
String shell = "/bin/bash";
// Create a ProcessBuilder object
ProcessBuilder processBuilder = new ProcessBuilder(shell, script);
// Set the script to run in its own directory
processBuilder.directory(new File(directory));
// Run the script
Process process = processBuilder.start();
I have written some code for executing .bat file. which contains some
commands like setting java classpath,etc..And finally there is one command
which runs a Java class file.The HelloWorld class converts some xml file and generating a new xml file in some folder. When I double click .bat file, it executes fine,
but when I try to run I am not getting any output as I was getting through
double click the .bat file. How to make a batch execute and probably it would be nice
if I could see the results through Java console.
Following is MyJava code to execute the .bat file
public void run2() {
try {
String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
Process p = Runtime.getRuntime().exec(commands);
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
And below the some commands which has been set to .bat file
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java/classes
java -cp test.jar;test2.jar test.HelloWorld
Tried with "/C" commad as well. It does not execute. Actually it does not give effect of double click the .bat file. Is there any other way that I can try with?
I can see the contents inside the .bat file through Eclipse console. But it does not give the desired output. Desired output means when I double click .bat file, it executes well. But through java call, I can see the contents only .
When using cmd.exe use /C-Parameter to pass command:
String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
according to this, the Windows CMD needs the /c argument, to execute commands like this. try this:
String []commands = {"cmd.exe","/c","C:/MyWork/Java/classes/run.bat"} ;
Windows uses \ backslash for Windows and MS-DOS path delimiter. Forward slash / is accepted by Java in the java.io package and translated to be a path delimiter, but will not be directly acceptable to Windows or accepted by the cmd.exe shell.
You may also need to specify either the working directory for the batch file to be executed in, or possibly a full path to the cmd.exe command interpreter.
See: Runtime.exec (String[] cmdarray, String[] envp, File dir)
String[] commands = {"C:\\Windows\\System32\\cmd.exe", "/c",
"C:\\MyWork\\Java\\classes\\run.bat"};
File workDir = new File( "C:/MyWork");
Process process = Runtime.getRuntime().exec( commands, null, workDir);
To verify if the batch file is run at all, add a pause command to the batch file. That will keep the window open so you can verify if the batch file is launched at all, and debug this stage-by-stage.
You do not read the error output of your batch file, therefore, you'll never see any error messages printed from there or from CMD.EXE itself. In addition, the sub-program may stall and just wait for you to read the error stream.
Please see related discussions here: How to make a java program to print both out.println() and err.println() statements?
I want to call shell script on windows environment using java code.
I am trying to execute code below to run my test script(not actual script):
Java Code:
public static void main (String args[]) {
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("C:\\cygwin\\bin\\bash -c '/cygdrive/d/scripts/test.sh'");
InputStream in = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
System.out.println("OUT:");
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
in = p.getErrorStream();
br = new BufferedReader(new InputStreamReader(in));
System.out.println("ERR:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
test.sh
#!/bin/bash
rm -rf ./test
But I am getting these error and script in not able to remove the directory.
ERR:
/cygdrive/d/ereader/scripts/test.sh: line 2: $'\r': command not found
/cygdrive/d/ereader/scripts/test.sh: line 3: rm: command not found
Another thing, when I run the script from the cygwin terminal it works fine. I checked the path variable they all are fine. But I try to execute same script through java code it gives error..
Now how to tell java program where to refer for rm commands?
The giveaway is the '\r' error.
Windows and Unix (which includes Mac and Linux) use different representations of a new line. Windows uses '\r\n' while Unix simply uses '\n'. Most programming editors account for this and only insert a '\n' so they work with Unix tools.
I would suggest retyping your shell script in another editor like Notepad++ (which only inserts '\n'), or make sure your current editor is set to use Unix newlines. You have to retype it or the bad '\r\n' sequences will get copied over. You might have some luck in doing a replace-all but that always acts flaky for me.
probably you will need to set the PATH variable first thing in the test.sh script. Make sure rm is in the PATH you set
Not really answer. You could try following to narrow down the problem
Use ProcessBuilder instead of Process. It is much more friendly to handle arguments.
Set absolute path to rm (/bin/rm ) in the script
remove using absolute path to directory or remove after verifying you are in the correct directory..
The bash prompt you have is result of cygwin.bat calling bash with --login. It will have path variables and other usesul stuff sources. bash -c does not do it.
Try launching bash.exe with bash -l -c <command> : This sources the bash profile.