我假设您在 Windows 操作系统系列下运行此应用程序(否则您将不得不稍微调整一下)。 Runtime.exec() 方法用于执行可执行命令。 dir, cd, copy, 并非如此......因此,它会触发您正在经历的异常。
cd 命令是 Windows 命令解释器cmd. 的一部分,它可以使用command.com 或cmd.exe 执行,具体取决于操作系统的版本。
因此,我们应该首先运行命令解释器,并将用户提供的命令(例如dir,cd,copy, ...)提供给它
这是一个执行此操作的程序。它检查os.name 环境变量以选择正确的命令解释器。我测试了 Windows NT 和 Windows 95。如果这两个都没有找到但仍然是 Windows 操作系统,那么我认为它是现代 Windows(例如 Windows 7 或 Windows 8)并且它正在使用cmd.exe.
import java.util.*;
import java.io.*;
class StreamGobbler extends Thread
{
InputStream is;
String type;
StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
public class GoodWindowsExec
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java GoodWindowsExec <cmd>");
System.exit(1);
}
try
{
String osName = System.getProperty("os.name" );
System.out.println("OS NAME IS " + osName);
String[] cmd = new String[3];
if( osName.equals( "Windows NT" ) )
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Windows 95" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
} else if (osName.toUpperCase().trim().contains("WINDOWS")) {
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
这是这个类的简单跑步者
public class GoodWindowsExecRunner {
public static void main(String[] args) {
//GoodWindowsExec.main(new String[] {"dir *.*"});
GoodWindowsExec.main(new String[] {"cd .."});
}
}
这是执行“cd ..”命令的结果
这是执行“dir .”命令的结果
有一篇关于java世界的优秀文章叫When Runtime.exec won't