如何在Java类中执行cmd命令?

时间:2012-12-25 08:59:04

标签: java process cmd runtime.exec

我想在java代码中调用cmd命令。我说:

String str ="C:/uploaded_files/111.txt";
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c",str});
System.out.println(str);

并且得不到111.txt。这很奇怪,因为当这段代码在jsp时,一切正常。什么可能是错的?

3 个答案:

答案 0 :(得分:3)

这段代码有什么问题。它完美地工作。打开并显示文件111.txt

的内容
try {
    String str ="C:/uploaded_files/111.txt";
    Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c",str});
    System.out.println(str);
    } catch (Exception ex) {}

请检查路径是否正确以及目录和文件是否未错过或拼写

答案 1 :(得分:0)

我希望它不是 cmd.exe 请试试这个:

String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = "C:/uploaded_files/111.txt";

Process p = Runtime.getRuntime().exec (command);

答案 2 :(得分:0)

如果你想在记事本中打开文件,试试这个。

String file = "C:/uploaded_files/111.txt";

Runtime.getRuntime().exec("cmd", "/c", "notepad.exe", file);

希望这是你想要的那个。