Java doesn't print out shell echo - java

I'm running a shell script using:
Runtime.getRuntime().exec(command);
Everything works fine, exept for the output. So, this script
echo "opening gedit..."
gedit
Opens gedit, but when running from Java I don't get any output. What is the problem?

String line;
Process p = Runtime.getRuntime().exec(...);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
As mentioned in Printing Runtime exec() OutputStream to console

Related

Show output while execute long-time running command Java without waiting RuntimeExec

I have command that takes about 4 minutes to complete execution. While executing the command from windows command prompt, it shows timing information and continuous output.
I want to show that output while running the command from my Java code.
Normal execution waits until the command exit and get the output. I want to get the output while running without waiting the command to finish.
Here is my code:
try{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(args);
String line="";
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
errorReader.lines().forEach(System.out::println);
process.waitFor();
System.out.println("---------------------------------------");
}
catch (Exception x){
System.out.println(x.getMessage());
}
Problem with this code is that it wits until the command ends then print all output at once.
The easiest solution is to stop using Runtime.exec, and use the more modern ProcessBuilder class instead. Its inheritIO() method will do exactly what you want:
ProcessBuilder builder = new ProcessBuilder(args);
builder.inheritIO();
Process process = builder.start();
You can’t read all of a process’s standard output or standard error at once. They can appear concurrently, and failing to read either one might or might not cause a process to hang. inheritIO() solves that problem.
For a reason I don't know about, The command I use, which is ffmpeg -i, to produce some resolutions of a video. It writes the output messages to the ErrorStream not OutputStream. When I printed the error stream first, I can see the output.
try{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(args);
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = err.readLine()) != null) {
System.out.println(line);
}
err.close();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
process.waitFor();
System.out.println("---------------------------------------");
}
catch (Exception x){
System.out.println(x.getMessage());
}

getting error from java

How can I call a shell script through java code?
I have writtent the below code.
I am getting the process exit code as 127.
But it seems my shell script in unix machine is never called.
String scriptName = "/xyz/downloads/Report/Mail.sh";
String[] commands = {scriptName,emailid,subject,body};
Runtime rt = Runtime.getRuntime();
Process process = null;
try{
process = rt.exec(commands);
process.waitFor();
int x = process.exitValue();
System.out.println("exitCode "+x);
}catch(Exception e){
e.printStackTrace();
}
From this post here 127 Return code from $?
You get the error code if a command is not found within the PATH or the script has no +x mode.
You can have the code below to print out the exact output
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s= null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
BufferedReader stdOut = new BufferedReader(new InputStreamReader(process. getErrorStream()));
String s= null;
while ((s = stdOut.readLine()) != null) {
System.out.println(s);
}
If you are getting an exit code, then your script is executed. There is a command that you are running inside of "Mail.sh", which is not succeccfully executed and returning a status code of 127.
There could be some paths that are explicitly set in your shell, but is not available to the script, when executed outside of the shell.
Try this...
Check if you are able to run /xyz/downloads/Report/Mail.sh in a shell terminal. Fix the errors if you have any.
If there are no errors when you run this in a terminal, then try running the command using a shell in your java program.
String[] commands = {"/bin/sh", "-c", scriptName,emailid,subject,body};
(Check #John Muiruri's answer to get the complete output of your command. You can see where exactly your script is failing, if you add those lines of code)

Running Bash from java does not work

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

Execute Command not work in Java

Execute Command worked well in Terminal, but not in Java code.
String cmd = "find -name javax.jar";
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null)
{
System.out.println("" + line);
}
System.out.println("Line : "+line);
When you spawn a process with
Runtime.getRuntime().exec(cmd);
the process is started from the same working directory as the Java process. If Java was run from a different working directory than you ran the find -name javax.jar in console, you will see different results.
i think you may try to add the path of find.
like find /var/tmp -name

Executing a command on the command line and reading the console output in Java

I need to get the hostId of my server using a Java program. Is there something in the Java API that is built-in which can help me do this?
lab.com$ hostid
f9y7777j -> How can I get this using java
The following would allow you to run a console command and store the result:-
ProcessBuilder pb = new ProcessBuilder("hostid");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
// Store returned string here.
}
reader.close();
Try the following code:
System.out.println(java.net.InetAddress.getLocalHost().getHostName());

Categories