在 JAVA 中运行 Shell 或系统命令

Mo3*_*o3z 1 java shell runtime exec ioexception

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();  
    }  
}
Run Code Online (Sandbox Code Playgroud)

我尝试了两种在JAVA中运行命令行的方式。他们都没有工作。谁能告诉我我做错了什么。我尝试了 3 个小时但没有成功:(

我不断收到此错误 File Not Found java.io.IOException: Cannot run program "command"

当我从 cmd 运行相同的命令时,它可以工作。我正在使用Windows..

请帮忙。谢谢你!

Shl*_*blu 5

尝试这个:

final Runtime rt = Runtime.getRuntime();
rt.exec(your command line here as a single String);
Run Code Online (Sandbox Code Playgroud)