Running Shell or System Command in JAVA

随声附和 提交于 2019-12-18 07:25:09

问题


private void myFunction(String userName){
    String fileName = this.generateFile(userName);
    String[] command = new String[4];
    command[0] = "cmd";
    command[1] = "/C";
    command[2] = "dir";
    command[3] = "7za a "+ userName+".7z  "+ fileName +" -p"+this.password;
    try {  
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader stdInput = new BufferedReader(new
        InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
        InputStreamReader(p.getErrorStream()));

        while ((s = stdError.readLine()) != null) {
        System.out.println(s);
        }

        ProcessBuilder proc = new ProcessBuilder(command[3]);
        proc.start();
    } catch(Exception e) {  
        System.out.println(e.toString());  
        e.printStackTrace();  
    }  
}

I tried both the way of running command line in JAVA. None of them worked. Can anyone enlighten me on what I am doing wrong. I tried for 3 hours but no luck :(

I keep getting this error File Not Found java.io.IOException: Cannot run program "command"

The same command when I run from cmd, it works. I am using Windows..

Please Help. Thank you!


回答1:


Try this:

final Runtime rt = Runtime.getRuntime();
rt.exec(your command line here as a single String);



回答2:


At the risk of repeating myself I'm gonna say it again: java.lang.ProcessBuilder is much better option




回答3:


Your command is not in any of the directories in the PATH variable. And it is likely not in the "current working directory" of your Java programms process. Either set PATH correctly, or give the full absolute path to the command which you want to run.



来源:https://stackoverflow.com/questions/7192595/running-shell-or-system-command-in-java

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