【问题标题】:Runtime.getRuntime().exec("ls ~") does not list the contents of home directoryRuntime.getRuntime().exec("ls ~") 没有列出主目录的内容
【发布时间】:2016-12-18 05:31:09
【问题描述】:

这是一台Linux机器,下面的代码没有任何输出,我很好奇为什么。 附言- 我没有读到需要转义的波浪号,但无论如何用反斜杠转义了波浪号,javac 指出了语法错误。

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

class Run {
    public static void main(String args[]) throws IOException {
        Process p = Runtime.getRuntime().exec("ls ~");
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

【问题讨论】:

  • ~ 被 shell 插值。
  • Process process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", "ls ~"}); 调用您的 shell 并扩展 ~,然后将其传递给 ls
  • 另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用exec 并使用ProcessBuilder 来创建进程。还将String arg 拆分为String[] args 以解决包含空格字符的路径之类的问题。

标签: java process runtime.exec


【解决方案1】:

这是因为 ~ 被 shell 替换为您的主目录的路径。您没有使用外壳。相反,就像您运行 ls '~' 一样,它给出了错误:

ls: cannot access '~': No such file or directory

事实上,当您将p.getInputStream() 更改为p.getErrorStream() 时,您会看到这种情况,这会使您的程序输出:

ls: cannot access '~': No such file or directory

【讨论】:

    【解决方案2】:

    您需要由 shell 插入 ~ 来获取主文件夹,而不是您可以从系统属性中读取 user.home,例如

    Process p = Runtime.getRuntime().exec("ls " + System.getProperty("user.home"));
    

    您也可以使用 ProcessBuilder 之类的方法

    ProcessBuilder pb = new ProcessBuilder("ls", System.getProperty("user.home"));
    pb.inheritIO();
    try {
        pb.start().waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2010-11-03
      • 2011-06-04
      • 2022-06-17
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 2015-08-28
      相关资源
      最近更新 更多