BufferedReader not working as expected - java

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();

Related

How to grep specific log from android device using Java code on runtime

I'm trying to grep log from android device on runtime to perform assertion, is there a way I can achieve the same, while passing below code seems working but its keep running, how can I end this after certain time
String log = "";
String str;
try {
String myStringArray[]= {"logcat", "| grep XYZ "};
Process process = Runtime.getRuntime().exec(myStringArray);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
str = br.readLine();
while (str != null) {
log += str;
str = br.readLine();
}
} catch (IOException e) {
System.out.println("Getting IOException .......");
}
return log;
} ```
I believe I'm missing something here

communicating with the process while executing a shell command with java

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());
}
}

Get the output from executed commands through android app

I'm performing the following code to execute linux commands in my android application that I'm creating:
public void RunAsRoot(String[] cmds){
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
}
os.writeBytes("exit\n");
os.flush();
}
I want to know if there is a way to know what the command is returning after it is executing. for example, if I do "ls" I would like to see what the command wold normally output.
try this code :
try {
Process process = Runtime.getRuntime().exec("ls");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder result=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(result.toString());
}
catch (IOException e) {}
Let's go by a "String function" example
String shell_exec(String s)
{
String line="",output="";
try
{
Process p=Runtime.getRuntime().exec(new String[]{"sh","-c",s});
BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=b.readLine())!=null){output+=line+"\r\n";}
}catch(Exception e){return "error";}
return output;
}
Now just use it:
String s=shell_exec("ls /data/data/com.mycompany.myapp");

How to get an exception thrown from another application in Java?

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.

Collect Linux command output

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

Categories