Read command output inside su process

后端 未结 3 723
余生分开走
余生分开走 2020-11-28 08:05

firstly I will present my situation. I need to execute \"su\" command in my android app and it works well. Then I need to execute \"ls\" command and read the output. I\'m do

3条回答
  •  借酒劲吻你
    2020-11-28 08:07

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

    Check this code mentioned here:

    How to run terminal command in Android application?


    try {
    // Executes the command.
    Process process = Runtime.getRuntime().exec("/system/bin/ls /sdcard");
    
    // Reads stdout.
    // NOTE: You can write to stdin of the command using
    //       process.getOutputStream().
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    int read;
    char[] buffer = new char[4096];
    StringBuffer output = new StringBuffer();
    while ((read = reader.read(buffer)) > 0) {
        output.append(buffer, 0, read);
    }
    reader.close();
    
    // Waits for the command to finish.
    process.waitFor();
    
    return output.toString();
    } catch (IOException e) {
    throw new RuntimeException(e);
    } catch (InterruptedException e) {
    throw new RuntimeException(e);
    }
    

    References

    this code GScript

提交回复
热议问题