简体   繁体   中英

Unable to run apktool command on shell from Java

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM