When i hit the curl in my cmd, its working. It returns a json response. But the output comes as blank for the below code.
String output = "";
String command = "curl -k -u snehasis:<API KEY> http://example.com";
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null)
{
output.concat(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return output;
Not sure what i am doing wrong. Help please?
Here:
output.concat(line + "\n");
You get back the concatenated String, but you don't change the value of output.
Java strings are immutable. The don't change by themselves. You need to change them.
Use:
output = output.concat(line + "\n");
Related
Im trying to run Yolo detector from a java GUI i wrote. I can start the detector using windows cmd like so:
cd <pathToYolo> \\ In my case named :C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64
darknet.exe detetctor test <pathToAConfigFile> <pathToAnotherConfigFile> <pathToModelDef> -dont_show <pathToImage>
I tried multiple aproaches. I used Runtime.getRuntime().exec() like so.
try {
String command = "darknet.exe detector test data\\obj.data cfg\\yolov4-obj.cfg backup\\rgbmodel\\yolov4-obj_last.weights -dont_show C:\\Users\\felix\\Desktop\\yoloTestSet\\RGBTest\\IMG_2392.jpg";
Process proc = Runtime.getRuntime().exec("cmd /c start /wait " + command, null,
new File("C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64"));
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
proc.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I also tried:
ProcessBuilder pb = new ProcessBuilder(
"cmd",
"/C",
"start",
"darknet.exe",
"detector",
"test",
"data\\obj.data",
"cfg\\yolov4-obj.cfg",
"backup\\rgbmodel\\yolov4-obj_last.weights",
"-dont_show",
"-ext_output",
"C:\\Users\\felix\\Desktop\\yoloTestSet\\RGBTest\\IMG_2392.jpg"
);
pb.directory(new File("C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64"));
try {
Process process = pb.start();
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String output = null;
while ((output = bufferedReader.readLine()) != null) {
System.out.println(output);
}
//wait for the process to complete
//process.waitFor();
//close the resources
//bufferedReader.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
Both will run the process and print the desired output on cmd and closes the cmd afterwards. So far its just what i want. My problem now is, how can read this output properly.
br.readLine()
seems to be null.
If I leafe out the "start" before the actuall command, I can read the first line of the output, then everything gets stuck, leaving out "cmd" gives me this error:
Cannot run program "darknet.exe" (in directory "C:\AI\Yolo_v4\darknet\build\darknet\x64"): CreateProcess error=2, The system cannot find the file specified
The doku is a bit short on what the "cmd /C start" part actually does.
I would appreciate some advice on what is the issue here and how to do that properly,
regards Felix
Thanks to Daniel Junglas hint, I found this to be a solution.
try {
String command = "C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64\\darknet.exe detector test C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64\\data\\obj.data C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64\\cfg\\yolov4-obj.cfg C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64\\backup\\rgbmodel\\yolov4-obj_last.weights -dont_show -ext_output C:\\Users\\felix\\Desktop\\yoloTestSet\\RGBTest\\IMG_2392.jpg";
Process proc = Runtime.getRuntime().exec(command, null,
new File("C:\\AI\\Yolo_v4\\darknet\\build\\darknet\\x64"));
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
while ((line = stdInput.readLine()) != null)
System.out.println(line);
proc.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Some of the desired output was inside the ErrorStream. Also you need full paths and do a minor change to YOLO itself, since there is an internal error raised. "cmd /c start" is not necassery.
I need to run command from my java application and process it's output.
The code is look like this:
public static void readAllOutput(){
try {
final String cmd = new String("find ~ -iname \"screen*\"");
System.out.println(cmd);
Process ps = Runtime.getRuntime().exec(cmd);
// ps.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(ps.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException /*| InterruptedException*/ e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I execute this command from OS I have a big output, but in my Java app the output is emty.
you need to use
getRuntime().exec( new String[] { "find", "~", "-iname","screen*"} );
or try
getRuntime().exec( new String[] { "find", "~", "-iname","\"screen*\""} );
inorder to accept arguments as double quotes.
I'm trying to work on a security system which needs remote debugging.So what I'm searching is a way to execute a code which is in a String,like the example below but with java.
try {
String Code = "rundll32 powrprof.dll, SetSuspendState";// the code we need to excecute
Runtime.getRuntime().exec(Code);
} catch (IOException e) {
}
String Code = "rundll32 powrprof.dll, SetSuspendState";
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(Code);
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();
}
System.out.println(output.toString());
Please refer the following URL for further information http://www.mkyong.com/java/how-to-execute-shell-command-from-java/
No friend you got it wrong.I really don't want to execute cmd codes.what i really want is to execute java commands.as a string which is passed as shown below.
example :
String code = "System.out.println("Test code")";
Runtime.getRuntime().exec(Code);
something like this.
Can someone help me in the below scenario,
I need to call a perl script from my java code. The perl script is an interactive code, which gets the input from the user during its execution and continues further to end. So, the example I have used is, the perl script when executed asks for the age by printing in the console "How old are you?", when the user enter some value say '26'. Then it prints "WOW! You are 26 years old!".
When I tried calling this script from my java code, the process waits till I give the value as 26 in the outputstream, while in the inputstream there is no value. Then finally when again I read the inputstream, i get the entire output of the script together. So, here can't I make it interactive?
I have went through many forums and blogs, but couldn't locate any, which exactly target my requirement.
Here is the java code
import java.io.*;
public class InvokePerlScript {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process;
try
{
process = Runtime.getRuntime().exec("cmd /c perl D:\\sudarsan\\eclips~1\\FirstProject\\Command.pl");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
out.write("23");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
process.waitFor();
if(process.exitValue() == 0)
{
System.out.println("Command Successful");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
System.out.println("Command Failure");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch(Exception e)
{
System.out.println("Exception: "+ e.toString());
}
}
}
Perl code is as below
$| = 1;
print "How old are you? \n";
$age = <>;
print "WOW! You are $age years old!";
Thanks in advance,
Sudarsan
Are you calling flush() on the OutputStream in Java after writing the values? If you don't, there's a good chance they'll just be held in the stream's buffer within the Java process, and so never make it to Perl (with the result that both processes end up waiting for the other's IO.)
(Depending on the implementation of the stream this may or may not be necessary, but it certainly wouldn't hurt - and I've been bitten by this in the past. Usually one doesn't need to be as careful, since flushing happens implicitly when close() is called, but here you can't close the stream after you've finished writing.)
It looks like you're trying to read a full line in this code:
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
...
However, in your perl code, you are not printing an endline character, so readLine never returns (as per the documentation).
How to send a command to the terminal through android app and get the output back? For example, sending "ls /" and getting the output to print it in the GUI?
You have to use reflection to call android.os.Exec.createSubprocess():
public String ls () {
Class<?> execClass = Class.forName("android.os.Exec");
Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
int[] pid = new int[1];
FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
String output = "";
try {
String line;
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
}
catch (IOException e) {}
return output;
}
Different solutions could be found here: http://code.google.com/p/market-enabler/wiki/ShellCommands
I've not tested them yet.
Try this answer there is way to run shell commands on android programmatically
https://stackoverflow.com/a/3350332/2425851