How to execute cmd command in Java class?

久未见 提交于 2020-01-05 07:17:27

问题


I want to call cmd command in java code. I say:

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?


回答1:


what's the problem with this code. It's perfectly working. opens and shows content of the file 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




回答2:


I hope It is not cmd.exe Please try this:

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

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



回答3:


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.



来源:https://stackoverflow.com/questions/14029187/how-to-execute-cmd-command-in-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!