gpt4 book ai didi

java - Runtime.getRuntime().exec ("ls ~") 未列出主目录的内容

转载 作者:行者123 更新时间:2023-12-02 03:09:54 25 4
gpt4 key购买 nike

这是一台 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 替换为您的主目录的路径。你没有使用外壳。相反,就像您运行了 ls '~' 一样,它给出了错误:

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

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

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

关于java - Runtime.getRuntime().exec ("ls ~") 未列出主目录的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41205780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com