I want to run a exe program from my Java application.I try this code for it.
I run the batch file and batch file runs the exe.
try {
String command = "C:\\tryfile\\Runprogram.bat";
// ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
int excode = p.waitFor();
System.out.println(excode + " asfasf");
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
The exe runs well and does what I want.(It insert from csv file to database with bcp).There is no problem about it.
But waitfor method returns 2147483647.
What is it?I have no idea about it.I know that if the exe run and finish without any error it returns 0 normally.But my exe returns 2147483647.
Any idea?
My bat file is here:
C:\tryfile\myprogram.exe
You are getting the exit code of the BAT, not the return code of the EXE. But you have not specified an exit code in your BAT so you get trash.
I don't have a windows box on hand but something like this should work
C:\tryfile\myprogram.exe
EXIT /B %ERRORLEVEL%
Check Batch files - Errorlevels
Related
Java code
try {
String command = "/opt/compress.sh param1 param2 param3";
Process ps = Runtime.getRuntime().exec(command);
ps.waitFor(60 * 5, TimeUnit.SECONDS);
br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
result = sb.toString();
log.info("shell logļ¼\n" + result);
}finally {
br.close();
}
shell Code
#Other business codes
zip -m -jP $3 ${zipOutPath} ${fileIputPath}
The workflow engine calls jar packages to execute Java code, and the zip command in the shell often fails. Manually executing the JAR package on the server is normal.Zip compresses only a CSV file,the file size is 2G.Try to enable shell Debug, only get -> addling XXx. CSV (%)
You are not consuming output streams properly so this may lead to freeze, and waitFor must be after reading STDOUT. Try using ProcessBuilder instead and see what errors it reports, it may help you to the next step:
ProcessBuilder pb = new ProcessBuilder(cmd);
// No STDERR => merge to STDOUT (or redirect elsewhere)
pb.redirectErrorStream(true);
Process p = pb.start();
try(var merged = p.getInputStream()) {
merged.transferTo(System.out);
}
// Check the executable worked:
int rc = p.waitFor();
if (rc != 0)
throw new RuntimeException("failed: "+Arrays.toString(cmd));
I'm playing a bit around with a small JAVA gui for the command line mode of cloudcompare.
Therefore I'm using a short snippet like these:
var processBuilder = new ProcessBuilder();
try {
var process = processBuilder
.command("open", "-a", "CloudCompare.app", "-n",
"--args", "-NO_TIMESTAMP", "-C_EXPORT_FMT", "LAS",
"-O", "/Users/se/pcl_1.las",
"-O", "/Users/se/pcl_2.las",
"-MERGE_CLOUDS")
.start();
String error, line;
BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = inputStream.readLine()) != null) {
System.out.println("line = " + line);
}
BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((error = errorStream.readLine()) != null) {
System.out.println("error = " + error);
}
var ret = process.waitFor();
System.out.printf("Program exited with code: %d", ret);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
But if I run it on macOS the command line window opens, the process runs normal, but I can't grab any of the informations in it. There is an option to write log files from cloudcompare. That works - the log file shows that all cloud processing steps are done.
Does anybody knows, how to grab the command line output?
As mentioned here, the /usr/bin/open command is not an option to grab the stdinput stream.
I change the command to /Applications/CloudCompare.app/Contents/MacOS/CloudCompare and it works.
The next question is, how to grab the InputStream with a thread. I tried some stack overflow topics, but it doesn't work at the moment, to get the output stream in realtime. It is flushed at the end of the CloudCompare process.
So i try to Execute an external program and capture the output.
Currently the part that execute command works fine (using .bat file) and i can see the output on the cmd window.
The part that need to read the output not and it seemt that it stack inside my while
This is what i have try:
String[] command = {"cmd.exe", "/C", "Start", "d:\\batFile.bat"};
Process process = Runtime.getRuntime().exec(command);
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Update
This is my .bat file:
docker volume create --name=mydb
timeout 3
docker run -d -p 27017:27017 -v mydb:/data/db mongo
timeout 3
Maybe you can try to redirect the output like this :
Process runtimeProcess1;
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C","Start","d:\\batFile.bat");
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
pb.redirectInput(Redirect.INHERIT);
runtimeProcess1 = pb.start();
int processComplete1 = runtimeProcess1.waitFor();
I'm trying to execute batch file in java.
My source is below:
List<String> comm = new ArrayList<String>();
comm.add("cmd");
comm.add("c:/Users/cointreau/workspace/pmd-bin-5.3.2/pmd-bin-5.3.2/bin/pmd.bat");
comm.add("-d");
comm.add("C:\\Users\\cointreau\\workspace\\counter\\src\\Counter.java");
comm.add("-f");
comm.add("xml");
comm.add("-R");
comm.add("java-codesize");
comm.add("-r");
comm.add("C:\\Users\\cointreau\\workspace\\counter\\report.xml");
ProcessBuilder probuilder = new ProcessBuilder( comm );
Process process = probuilder.start();
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Wait to get exit value
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the original command line is this,
c:/Users/cointreau/workspace/pmd-bin-5.3.2/pmd-bin-5.3.2/bin/pmd.bat -d C:\\Users\\cointreau\\workspace\\counter\\src\\Counter.java -f xml -R java-codesize -r C:\\Users\\cointreau\\workspace\\counter\\report.xml`
pmd.bat is the batch file what i want to execute and the remainders are just parameters for the bat file.
The only output I can see is just exit Value is 1.
When I execute this command line in cmd, it runs properly but not in my java source.
What should I do?
Thanks for your help in advance.
Try adding the /C option to carry out the batch command
comm.add("cmd");
comm.add("/c");
comm.add("c:/Users/cointreau/workspace/pmd-bin-5.3.2/pmd-bin-5.3.2/bin/pmd.bat");
...
I'm using UBUNTU/LINUX
I'm trying to build swing application for myself(this app need to work other platforms too) and i can not execute some commands on java.I tried to execute "java -version"
Here is my code:
Runtime run = Runtime.getRuntime();
Process p = run.exec("java -version");
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
for (String output = br.readLine(); output != null; output = br.readLine()) {
System.out.println(output);
}
} catch (IOException e) {
System.out.println(e);
}
It returns blank page no output!
However i can execute run.exec("ls") / or ("gedit") and so on... and I GET DATA
Also i can execute internal programs that in my computer.
Why i cant execute .sh files or built-in java commands and getting blank page?
You should use ProcessBuilder to mix standard and error outputs:
ProcessBuilder run = new ProcessBuilder("java", "-version");
run.redirectErrorStream(true);
Process p = run.start();
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
for (String output = br.readLine(); output != null; output = br.readLine()) {
System.out.println(output);
}
} catch (IOException e) {
System.out.println(e);
}
Check that java parent directory is in your PATH variable (output System.getenv("PATH")) or use a full path to the binary.
For script, use /bin/sh like that ProcessBuilder run = new ProcessBuilder("/bin/sh", "/path/to/your/script");
All path can be absolute starting with /, or relative (without /) to System.getProperty("user.dir").
The jvm itself directs output to the error stream
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {