I'm going to execute a shell command from java and i need to pass arguments to the output stream while executing the command..
following is the shell command
./darknet detect cfg/yolo-voc.2.0.cfg backup/yolo-voc_20000.weights
when executing this command it is yielding for the path of the image file in the terminal i can provide the path of the image as follows
Loading weights from backup/yolo-voc_21000.weights...Done!
Enter Image Path:
when executing from the terminal i can provide the path there.
I managed to execute this command withing the java process and also i can get an output when i provide an image uri with the command. here is the code
public static void execCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
//reader.readLine();
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
s.add(line);
}
// proc.waitFor();
} catch (IOException e) {
System.out.println("exception thrown: " + e.getMessage());
}
}
but what I want is provide the image path at the runtime not beginning of the execution of the command..
tried with writing to the output stream as below still no luck
public static void execCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
writer.append("data/test2.jpg");
writer.newLine();
//reader.readLine();
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
s.add(line);
}
// proc.waitFor();
} catch (IOException e) {
System.out.println("exception thrown: " + e.getMessage());
}
}
You need to call writer.flush() in order to actually output something to the underlining InputStream
Therefore your code should look like:
public static void execCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String line = "";
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
writer.append("data/test2.jpg");
writer.newLine();
// **** add flush here ****
writer.flush();
// and remember to close your resource too
writer.close();
//reader.readLine();
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
s.add(line);
}
// ***** close your reader also ****
reader.close();
// proc.waitFor();
} catch (IOException e) {
System.out.println("exception thrown: " + e.getMessage());
}
}
Related
I have the following code which prints the output of the DataIntegrationV8.jar to the JTextArea. Is it possible to print an exception thrown by that program in the same JTextArea?
protected Integer doInBackground() throws Exception {
Process process;
InputStream iStream;
try {
//run the DataIntegration.jar
process = Runtime.getRuntime().exec("java -jar DataIntegrationV8.jar sample.xml");
istream = process.getInputStream();
} catch (IOException e) {
throw new IOException("Error executing DataIntegrationV8.jar");
}
//get the output of the DataIntegration.jar and put it to the
//DataIntegrationStarter.jar form
InputStreamReader isReader = new InputStreamReader(iStream);
BufferedReader bReader = new BufferedReader(isReader);
String line;
while ((line = bReader.readLine()) != null) {
jtaAbout.append(line + "\n");
}
Thread.sleep(1);
return 42;
}
By default exception stacktraces are displayed to System.err. You could include the output from the ErrorStream to the JTextArea.
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String errorLine = null;
while ((errorLine = error.readLine()) != null) {
jtaAbout.append(errorLine + "\n");
}
You could check the error code returned by the program and it it is not zero, you know the output is a java stacktrace as the program terminated ...... poorly.
I'm trying to launch a process in java, read the output, write to the program, then read what it responds with. From all the other answers on SO, this is what I have come up with:
class Main
{
public static void main(String[] args) {
String line = "";
try {
ProcessBuilder pb = new ProcessBuilder("C:\\myProgram.exe");
Process p = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
output.write("foo");
output.newLine();
output.flush();
while ((line = input.readLine()) != null) {
System.out.println(line);
}
p.destroy();
}
catch (IOException e){
}
}
}
It launches the program, and gives me the output just as expected.
When i write foo, I expect the program to come back with another response, but it never does.
What am I doing wrong?
The below code is not getting executed completely after this line " bufferedReader.readLine(); ". The Program works fine when i execute the system command with
out mentioning IPAddress of the remote PC.
class Test
{
public static void main(String arg[])
{
Process p;
Runtime runTime;
String process = null;
try {
runTime = Runtime.getRuntime();
p = runTime.exec("sc \\xx.xx.xx.xx query gpsvc"); // For Windows
InputStream inputStream = p.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
process = "&";
while (line != null) {
line = bufferedReader.readLine();
process += line + "&";
}
StringTokenizer st = new StringTokenizer(proc, "&");
System.out.println("token size "+st.countTokens());
while (st.hasMoreTokens()) {
String testData = st.nextToken();
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
}
} catch (IOException e) {
System.out.println("Exception arise during the read Processes");
e.printStackTrace();
}
}
}
Check your command inside exec method
p = runTime.exec("sc \\xx.xx.xx.xx query gpsvc");
The syntax is wrong here and if you execute this from command prompt, you will be prompted with the below question.
Would you like to see help for the QUERY and QUERYEX commands? [ y | n ]:
And the program wouldn't return until you enter y or n. Since the program is not terminating, you wouldn't be able to read the console output and that's the reason your program is getting stuck on String line = bufferedReader.readLine();
I trying to run multiple command shells from Java. I am able to do that (and get the output in the console using PrintWriter). However, I want to be able to get the output of each command in a separate String. Is that possible?
Here is a part of the code :
File wd = new File("/bin");
Process proc = null;
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd ..");
out.println("ls");
System.out.println("moving to /var directory");
out.println("cd /var/");
out.println("ls");
//get output of ls command in string variable
out.println("cd ..");
out.println("cd /etc/");
out.println("ls -a");
out.println("ps");
out.println("exit");
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
Have you tried putting a section like
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
builder.append(line).append("\n");
}
String commandOutput = builder.toString();
after each command? Is that roughly what you are trying to achieve?
I am now on a linux machine. I have a Java program which would run some linux command, for example ps, top, list or free -m.
The way to run a command in Java is as follows:
Process p = Runtime.getRuntime().exec("free -m");
How could I collect the output by Java program? I need to process the data in the output.
Use Process.getInputStream() to get an InputStream that represents the stdout of the newly created process.
Note that starting/running external processes from Java can be very tricky and has quite a few pitfalls.
They are described in this excellent article, which also describes ways around them.
To collect the output you could do something like
Process p = Runtime.getRuntime().exec("my terminal command");
p.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
String output = "";
while ((line = buf.readLine()) != null) {
output += line + "\n";
}
System.out.println(output);
This would run your script and then collect the output from the script into a variable. The link in Joachim Sauer's answer has additional examples of doing this.
As for some command need to wait for a while, add p.waitFor(); if necessary.
public static void main(String[] args) {
CommandLineHelper obj = new CommandLineHelper();
String domainName = "google.com";
//in mac oxs
String command = "ping -c 3 " + domainName;
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
The technicalities of calling an external process are quite involved. The jproc library helps abstracting over these by automatically consuming the output of the command and providing the result as a string. The example above would be written like this:
String result = ProcBuilder.run("free", "-m");
It also allows to set a timeout, so that your application isn't blocked by an external command that is not terminating.
public String RunLinuxGrepCommand(String command) {
String line = null;
String strstatus = "";
try {
String[] cmd = { "/bin/sh", "-c", command };
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = in.readLine()) != null) {
strstatus = line;
}
in.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
String stackTrace = sw.toString();
int lenoferrorstr = stackTrace.length();
if (lenoferrorstr > 500) {
strstatus = "Error:" + stackTrace.substring(0, 500);
} else {
strstatus = "Error:" + stackTrace.substring(0, lenoferrorstr - 1);
}
}
return strstatus;
}
This functioin will give result of any linux command