I am trying to use the apktool from a Java program. I'm using this for creating a web service. However this command does not run on the shell from the Java program.
String cmd = "apktool d /home/ridhima/Test.apk" ;
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line = reader.readLine()) != null)
{
System.out.print(line + "\n");
}
p.waitFor();
}
catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
The command works perfectly fine directly from the shell.
Thanks but it works fine now. Since apktool is a wrapper script, it is probably not being recognized through the java program. Extracting the apktool.jar directly works.
try {
ProcessBuilder pb = new ProcessBuilder("/home/ridhima/java/jdk1.8.0/bin/java", "-jar", "apktool.jar","d","test.apk");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
p.waitFor();
}catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
You maybe should wait for the process to complete
String cmd = "apktool d /home/ridhima/Test.apk" ;
try {
Process p = Runtime.getRuntime().exec(cmd);
// You maybe should wait for the process to complete
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line = reader.readLine()) != null)
{
System.out.print(line + "\n");
}
}
catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
Or you can use ProcessBuilder for the same task
public class Main {
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
// Create ProcessBuilder instance for UNIX command ls -l
java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("ls", "-l");
// Create an environment (shell variables)
java.util.Map env = processBuilder.environment();
env.clear();
env.put("COLUMNS", "3");
processBuilder.directory(new java.io.File("/Users"));
java.lang.Process p = processBuilder.start();
}
}
Related
The program is stuck at p2.waitFor() (I tested with printing strings before and after)
public void score() {
this.toXML();
try {
Process p = Runtime
.getRuntime()
.exec("python sumocfg_maker.py Carrefour.net.xml Detectors.det.xml edgedata.csv -ef");
p.waitFor();
Process p2 = Runtime.getRuntime().exec("python simulation.py");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p2.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
and simulation.py is
import os
os.system('cmd /c "sumo -c Simulation.sumocfg --duration-log.statistics --log duration.txt)
The simulation.py runs fine on its own. When I put the command in simulation.py in java, I get the same problem.
The System.out.println(line); prints out "Success" and then nothing
I left out code from simulation.py that saves a file that the java reads right after the p2.wait(), and without the p2.wait() the file never changes.
You have
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
But you need
BufferedReader input = new BufferedReader(new InputStreamReader(p2.getInputStream()));
since p is already finished, the bufferedreader will wait but never receive anything.
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 want to get terminal history
So I did this
Runtime rt = Runtime.getRuntime();
pr = rt.exec("/bin/bash -c \"history -c\"");
pr.waitFor();
rt.exec("/usr/bin/xterm");
but there is problem with pr = rt.exec("/bin/bash -c \"history -c\""); , it's not clearing the previous history nither of xterm nor my normal terminal.
Also when I try to print the history it returns nothing (no errors)
p = Runtime.getRuntime().exec("/bin/bash -c \"history\"");
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("printing");
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
I also tried
String[] commands = new String[]{"/bin/sh","-c", "history -c" ,"xterm"};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
} catch (IOException e1) {
e1.printStackTrace();
}
still not clearing history.
You can remove the history file yourself by getting the $HISTFILE environment variable. This will always get the correct history file for different shells. I believe the issue you're having is that the you may be using a different shell or have changed your history file location.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RemoveShellHistory {
public static void main(String[] args) {
RemoveShellHistory obj = new RemoveShellHistory();
final String shellPath = System.getenv("SHELL");
String shell = shellPath.substring(shellPath.lastIndexOf("/")+1, shellPath.length());
final String home = System.getenv("HOME");
String command = "rm -v " + home + "/." + shell + "_history";
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();
}
}
Assuming that your java app runs by the same user possessing the .bash_history file:
To delete.
new File(System.getProperty("user.home"), ".bash_history").delete();
To clean (Handle the checked exception at your will).
FileWriter writer = new FileWriter(
new File(System.getProperty("user.home"), ".bash_history"));
writer.write("");
writer.close();
How to call .scpt(applescript) file from java and pass argument into scpt file from java using
Runtime.getRuntime.exec() method.
Process result = Runtime.getRuntime().exec(cmdArray);
String[] args = {"/usr/bin/osascript", "/Users/uname/Library/Preferences/WebApp/Local\\ Store/spawn/Terminal.scpt" "args1", "args2" "args3" "false"};
Process result = Runtime.getRuntime().exec(args);
I cannot check this on Mac but the following answer works on windows:
List<String> list = new LinkedList<String>();
list.add("java");
list.add("-version");
ProcessBuilder pb = new ProcessBuilder(list);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream())));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e) {
System.out.println(e);
}
You can also read:
Difference between ProcessBuilder and Runtime.exec()
http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
This question already has answers here:
Executing a Java application in a separate process
(9 answers)
Closed 7 years ago.
Is there a way to run this command line within a Java application?
java -jar map.jar time.rel test.txt debug
I can run it with command but I couldn't do it within Java.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
You can also watch the output like this:
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.
EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:
String[] command = new String[] {
"choice",
"/C",
"YN",
"/M",
"\"Press Y if you're cool\""
};
String inputLine = "Y";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write(inputLine);
writer.newLine();
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:
Press Y if you're cool [Y,N]?Y
To avoid the called process to be blocked if it outputs a lot of data on the standard output and/or error, you have to use the solution provided by Craigo. Note also that ProcessBuilder is better than Runtime.getRuntime().exec(). This is for a couple of reasons: it tokenizes better the arguments, and it also takes care of the error standard output (check also here).
ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();
// Watch the process
watch(process);
I use a new function "watch" to gather this data in a new thread. This thread will finish in the calling process when the called process ends.
private static void watch(final Process process) {
new Thread() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
Problems with Runtime.exec()
what about
public class CmdExec {
public static Scanner s = null;
public static void main(String[] args) throws InterruptedException, IOException {
s = new Scanner(System.in);
System.out.print("$ ");
String cmd = s.nextLine();
final Process p = Runtime.getRuntime().exec(cmd);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
}
Have you tried the exec command within the Runtime class?
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")
Runtime - Java Documentation
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");