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

前端 未结 3 737
北荒
北荒 2021-01-01 04:38

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 direc

相关标签:
3条回答
  • 2021-01-01 05:20

    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(); 
        }
    }
    
    0 讨论(0)
  • 2021-01-01 05:32

    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.

    0 讨论(0)
  • 2021-01-01 05:38

    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.

    0 讨论(0)
提交回复
热议问题