Android Runtime.getRuntime().exec() to nav through directories

折月煮酒 提交于 2019-12-01 03:24:54

问题


So I want to be able to write an app that can turn on and display logcat messages, dmesg, and also be able to run commands like 'ls' 'cat' 'echo' 'cd.'

If I do the following:

nativeProc = Runtime.getRuntime().exec("ls\n");
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(nativeProc.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(nativeProc.getInputStream()));
        String line = null;

        while ((line = in.readLine()) != null) {  
            full = full + "\n" + line;
        }

I can put the text "full" to a Text View and see the root directory.

However, that's about all I can do. Let's say I want to find a directory, and change to it, I'm having trouble.

So if I do this:

nativeProc = Runtime.getRuntime().exec("ls\n");
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(nativeProc.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(nativeProc.getInputStream()));
        String line = null;

        while ((line = in.readLine()) != null) {  
            full = full + "\n" + line;
        }
        /* Code here to confirm the existing of a directory*/


        nativeProc = Runtime.getRuntime().exec("cd tmp\n");
        BufferedReader in2 = new BufferedReader(new InputStreamReader(nativeProc.getInputStream()));
        line = null;
        String test = "\nStart1:\n";
        while ((line = in2.readLine()) != null) {  
            test = test + "\n" + line;
        }

I get nothing for both "full" and "text"

Any ideas?


回答1:


You can execute ls with provided path for which folders should be listed

Runtime.getRuntime().exec(new String[] { "ls", "\\tmp"});



回答2:


The current working directory is associated with the current process. When you exec("cd tmp") you are creating a process, changing its directory to "tmp", and then the process exits. The parent process' working directory doesn't change.

See this for a more general discussion of changing the current working directory in Java.




回答3:


How about writing a shell file which checks for existence of the file and all other implementaion in this file and added it to sdcard and trigger the shell file from java using getRuntimr.exec().you can also pass parameters to it.



来源:https://stackoverflow.com/questions/4618631/android-runtime-getruntime-exec-to-nav-through-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!