java 如何在Java类中执行cmd命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14029187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute cmd command in Java class?
提问by Kliver Max
I want to call cmd command in java code. I say:
我想在java代码中调用cmd命令。我说:
String str ="C:/uploaded_files/111.txt";
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c",str});
System.out.println(str);
And dont get 111.txt
. Its strange because when this code was in jsp
all works fine. What can be wrong?
不要得到111.txt
。这很奇怪,因为当这段代码jsp
全部工作正常时。有什么问题?
回答by Nidhish Krishnan
what's the problem with this code. It's perfectly working. opens and shows content of the file 111.txt
这段代码有什么问题。它完美地工作。打开并显示文件 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) {}
please check whether the path is correct and whether the directories and files are not missed or spelled
请检查路径是否正确,目录和文件是否没有遗漏或拼写
回答by Harish Raj
I hope It is not cmd.exePlease try this:
我希望它不是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);
回答by Sri Harsha Chilakapati
If you want to open the file in notepad try this.
如果你想在记事本中打开文件试试这个。
String file = "C:/uploaded_files/111.txt";
Runtime.getRuntime().exec("cmd", "/c", "notepad.exe", file);
Hope it's the one you want.
希望这是你想要的。