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()))) {
Related
i am running jdk on windows 7. I try to run a external software (pocketsphinx_continous.exe) within my java application. The software runs permanently (pocketsphinx_continous.exe) and prints some output to the console which i like to read by my java application.
if i run "pocketsphinx_continous.exe" with some params from the commandline all works well and i see the output from the software. After killing the process, i try to run it within my java application. But java print no output to the console.
This is my code:
public void start(){
try {
Runtime rt = Runtime.getRuntime();
String[] commands = {"D:/cmusphinx/pocketsphinx/bin/Release/x64/pocketsphinx_continuous.exe", "-hmm", "d:/cmusphinx/pocketsphinx/model/en-us/en-us", "-lm", "d:/cmusphinx/pocketsphinx/model/en-us/en-us.lm.bin", "-dict", "d:/cmusphinx/pocketsphinx/model/en-us/cmudict-en-us.dict", "-samprate", "16000/8000/48000", "-inmic", "yes"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Java will only print "Here is the standard output of the command:" and nothing more. But it wont crash, its still running without any errors. It seems to me java will wait until the executed command is finished until it prints anything. But the software will run permanently and print some times new results ...
Any ideas?
Best regards
Mike
I suggest you do the following:
Process p = null;
ProcessBuilder b = new ProcessBuilder("D:/cmusphinx/pocketsphinx/bin/Release/x64/pocketsphinx_continuous.exe -hmm d:/cmusphinx/pocketsphinx/model/en-us/en-us -lm d:/cmusphinx/pocketsphinx/model/en-us/en-us.lm.bin -dict d:/cmusphinx/pocketsphinx/model/en-us/cmudict-en-us.dict -samprate 16000/8000/48000 -inmic yes");
try {
p = b.start();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ( (line = output.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Using ProcessBuilder you don't have to separate parameters. Just copy the whole command in a String.
I have the following bash script, example.sh that has some lines of code.To reproduce what I need let's say that I have in the script the following lines:
#!/bin/bash
echo First part of program
sleep 3
echo Second part of program
So, when I run this directly from terminal I get the first part printed to the screen(First part of program) then wait 3 seconds and after that I get the next part on the screen(Second part of program). When I run this in java, I execute the scipt, wait 3 seconds then I get both parts printed on screen. Is there a way to get the same effect as when running from terminal?
EDIT!
This is my code:
public void executeCommand(String command) {
String line;
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
setOutput(output.toString());
output = new StringBuffer();
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
line="";
while ((line = error.readLine())!= null) {
output.append(line + "\n");
}
setError(output.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
If you start your script with the Process-Class then you can fetch the output of the script with for example:
ProcessBuilder pb = new ProcessBuilder("<bashname>", "<scriptpath>");
Process p = pb.start();
OutputStream ops = p.getOutputStream();
There must be the output immediatly.
SOLVED: redirect output and error into files using:
ProcessBuilder builder = new ProcessBuilder("sh",command);
builder.redirectOutput(new File("out.txt"));
builder.redirectError(new File("err.txt"));
try{
Process p = builder.start();
}catch(IOException e){
e.printStackTrace();
}
I have this bash:
#!/bin/bash
# File to be tagged
inputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/Text.txt"
#inputfile="test/SampleInputs/longParagraph.txt"
# Tagged file to be created
#outputfile="test/SampleOutputs/NERTest.conll.tagged.txt"
outputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/1.Generate-Basic-Questions/Tagged-Named-Entites-Text.txt"
# Config file
#configfile="config/conll.config"
configfile="config/ontonotes.config"
# Classpath
cpath="target/classes:target/dependency/*"
CMD="java -classpath ${cpath} -Xmx8g edu.illinois.cs.cogcomp.LbjNer.LbjTagger.NerTagger -annotate ${inputfile} ${outputfile} ${configfile}"
echo "$0: running command '$CMD'..."
$CMD
When I run either java codes below they do not give any errors but they just show the bash file in my Eclipse Console, in other words they do not run the bash !! and the value for process.exitValue() is 1, by the way, my OS is CentOS, linux.
Firs JAVA code :
try {
Process process = new ProcessBuilder(command).start();
process.waitFor();
System.out.println(process.exitValue());
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
}
} catch (Exception e) {
System.out.println(e);
}
Second JAVA code :
String command = "/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/"
+ "SinaGolestanirad-Project/1.Generate-Basic-Questions/1.IllinoisNerExtended-DO-NOT-OPEN-BY-ECLIPSE/plaintextannotate-linux.sh";
StringBuffer output = new StringBuffer();
Process p;
try {
String[] cmd = new String[]{"/bin/bash",command};
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output.toString());
} catch (Exception e) {
e.printStackTrace();
}
I also checked the bash file permission and it is executable as a program.
How can I run the bash file? The bash should run another program written in java.
-- LeBarton what is the exit code?
Check the output of p.exitValue()
p.waitFor()
InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream());
While (inputStreamReader.ready()) { System.out.println(inputStreamReader.read(); }
This will show you the error output. Add this to the bottom below the try.. catch.
You will see the output that you would see on the command line. It will help you narrow down the error.
I found a link which may help, if your bash read some environmental variables.
$PATH variable isn't inherited through getRuntime().exec
I am running a script in a java program using:
Runtime.getRuntime().exec()
I am able to open the terminal application using this.
If I give command to run the script. It's happening but I am not able to get the logs in the terminal. I am using MAC. I want to get the logs in the terminal.
You can use a Process variable to get what return from that command, and use method such as: getInputStream(), getOutputStream(), getErrorStream(). Example:
Process p = null;
try {
p = Runtime.getRuntime().exec(....your stuff here)
p.getOutputStream().close(); // close stdin of child
InputStream processStdOutput = p.getInputStream();
Reader r = new InputStreamReader(processStdOutput);
BufferedReader br = new BufferedReader(r);
String line;
while ((line = br.readLine()) != null) {
//System.out.println(line); // the output is here
}
p.waitFor();
}
catch (InterruptedException e) {
...
}
catch (IOException e){
...
}
finally{
if (p != null)
p.destroy();
}
The Process object returned by the method call above has an getInputStream() method (as well as ones for the error and output streams). You have to read from those if you want to grap the inputs and outputs of your script.
For reference: http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html
in terminal, using > to output the log to file. For example: ls / > rootfolder.txt
Using that way, you can output the log to file and then read the log from the file.
I'm trying to execute a simple batch file from java using Runtime.getRuntime().exec(command);
but facing issues,
below is my code snippet
public class Path {
public static void main(String args[]){
String[] command = new String[3];
command[0]="cmd";
command[1]="/C";
command[2]="D:/alt/a.bat";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
and the batch a.bat has ant -f runme.xml test in it
and runme.xml resides in D:/alt physical location which has a target test, so far so good
but when i try to execute the java code above, below is the ouput
D:\RCPStack\Path>ant -f runme.xml test Buildfile: runme.xml does not
exist! Build failed
when i execute manually it works fine,seems to be the problem is with the code
below is manual execution output
how to tackle this(i don't know if the code is incorrect) and handle as a best practice
Try to use the method Runtime.exec(String cmd, String[] envp, File dir)
to set the working directory to D:/alt/.
This is because Ant must be executed in the directory where runme.xml is so Ant can find it.
p=Runtime.getRuntime().exec("cmd /c ant -f runme.xml test", null, new File("D:/alt"));//works
or
p=Runtime.getRuntime().exec("cmd /c a.bat", null, new File("D:/alt"));//works