【发布时间】:2015-05-18 13:55:16
【问题描述】:
我是 java 初学者,遇到了一些问题。我已经阅读了几个关于这个主题的主题,但没有一个对我有用。这是我的代码:
try
{
Console console = System.console();
String command;
while(true)
{
command = console.readLine("Enter input:");
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
catch(Exception e) {}
所以我正在尝试制作一个 java 程序并在其中运行终端命令(我使用的是 linux)。该程序适用于“ls”“ps ef”等命令,但当我键入“cd”时它不起作用。我知道 cd 会产生不同的进程,应该这样使用:“Runtime.exec(String command, String[] envp, File dir)”。我的问题是:
如何让我的程序运行各种终端命令?对不起,如果问题听起来很傻。谢谢。
【问题讨论】:
-
一个问题是:“cd”不是命令;这是你的shell的一个功能!当像你一样从 Java 运行命令时;没有壳!因此它不起作用!还有一件事:你的项目可能真的只是学习 Java 概念;但总的来说:允许用户提供任何类型的命令,然后只执行它们......是一个非常糟糕的主意。
-
您可能还想查看此线程。 stackoverflow.com/questions/31776546/…