Java Runtime.getRuntime().exec() fails after calling it several hundred times

守給你的承諾、 提交于 2019-12-18 13:35:50

问题


I have a Java program that executes Runtime.getRuntime().exec("ls -l"); many times, once for each directory in the system.

My test system has more than 1,000 directories and Runtime.getRuntime().exec("ls -l"); seems to error out after 480 directories or so. The error message I'm getting is is "Error running exec(). Command: [ls, -l] Working Directory: null Environment: null". I'm guessing it's running out of some required system resources or is it? Is there any way to process all directories without erroring out?

Relative comment from an answer:

I should clarify that I was using Android SDK's adb.exe. I wanted to execute something like Runtime.getRuntime().exec("adb shell ls -l") multiple times on different directories.


回答1:


You should explicitly close the input/output streams when using Runtime.getRuntime().exec.

Process p = null;
try {
    p = Runtime.getRuntime().exec("ls -l");
    //process output here
    p.waitFor();
} finally {
    if (p != null) {
        p.getOutputStream().close();
        p.getInputStream().close();
        p.getErrorStream().close(); 
    }
}



回答2:


It would be better to use java.io.File and the appropriate methods on those classes for walking and manipulating the file system.

You don't say why you are doing this degenerate behavior this way but here is an example of listing all the files in a tree.




回答3:


I have a Java program that executes Runtime.getRuntime().exec("ls -l"); many times, once for each directory in the system.

Why? Something wrong with File.listFiles()?

You don't need to execute 'ls' even once.



来源:https://stackoverflow.com/questions/9572025/java-runtime-getruntime-exec-fails-after-calling-it-several-hundred-times

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