Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getRuntime().exec() does nothing

Tags:

java

I want a java program to execute the following shell command:

apktool.jar d /path/to/my/app.apk

This command perfectly works when executing it directly on command line.

Java Code:

public static void main(String[] args) {

    String command = "apktool d /path/to/my/app.apk";
    try {
        Runtime.getRuntime().exec(command);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

There is no error, no exception. Nothing happens and i have the impression that I already searched the entire internet for a solution. Does anybody know what I am doing wrong? A simple command like

mkdir /path/to/a/new/folder

works without problems.

I tried the same using ProcessBuilder:

try {
    Process process = new ProcessBuilder(command).start();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

This time i only get "Cannot run program "apktool d /path/to/my/app.apk, No such file or directory". I can't even run the mkdir command.

like image 471
null Avatar asked Sep 04 '26 01:09

null


1 Answers

You need to call the jar with java.exe, and you're not doing that. Also you need to trap the input and error streams from the process, something you can't do the way you're running this. Use ProcessBuilder instead, get your streams and then run the process.

For example (and I can only do a Windows example),

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class ProcessEg {
   private static Process p;

   public static void main(String[] args) {
      String[] commands = {"cmd", "/c", "dir"};
      ProcessBuilder pBuilder = new ProcessBuilder(commands);
      pBuilder.redirectErrorStream();

      try {
         p = pBuilder.start();
         InputStream in = p.getInputStream();
         final Scanner scanner = new Scanner(in);
         new Thread(new Runnable() {
            public void run() {
               while (scanner.hasNextLine()) {
                  System.out.println(scanner.nextLine());
               }
               scanner.close();
            }
         }).start();
      } catch (IOException e) {
         e.printStackTrace();
      }
      try {
         int result = p.waitFor();
         p.destroy();
         System.out.println("exit result: " + result);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }
}
like image 82
Hovercraft Full Of Eels Avatar answered Sep 05 '26 15:09

Hovercraft Full Of Eels