Java Runtime.getRuntime (). Exec () exits after being called several hundred times

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

My test system contains more than 1000 directories and Runtime.getRuntime (). exec ("ls -l"); it seems an error after 480 directories or so. The error message I get is "Error starting exec (). Command: [ls, -l] Working directory: null Environment: null". I assume that he is running out of some required system resources or not? Is there a way to handle all directories without errors?

Relative comment from the answer:

I must clarify that I used the Android SDK adb.exe. I wanted to execute something like Runtime.getRuntime (). exec ("adb shell ls -l") several times in different directories.

+4
source share
3 answers

You must explicitly close I / O 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(); } } 
+7
source

It is better to use java.io.File and the appropriate methods for these classes to walk and manage the file system.

You are not saying why you are doing this degenerate behavior this way, but here is an example of listing all the files in a tree .

+3
source

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

Why? Is there something wrong with File.listFiles() ?

You do not need to execute "ls" even once.

0
source

Source: https://habr.com/ru/post/1399844/


All Articles