Java cmd shutdown CreateProcess error = 2

时间:2015-12-11 08:03:27

标签: java cmd

我最近尝试使用java中的cmd命令重新启动/关闭pc,但得到CreateProcess error=2。 我使用StringBuilder,因为我需要在cmd命令中使用""

public class CMDTest {
    public static void main(String[] args) throws IOException {
        startCmd();
    }

    public static void startCmd() throws IOException {
        String a = "shutdown -s -t 120 -c ";
        String b = "\"Your computer will restart. Cause something .\"";
        String g = "";

        StringBuilder sbuilder = new StringBuilder();
        sbuilder.append(a);
        sbuilder.append(b);
        String finall = sbuilder.toString(); 
        System.out.println(finall);

        Runtime.getRuntime().exec(new String[]{finall, g});
        System.out.println(g);

        Process p = Runtime.getRuntime().exec(new String[]{finall, g});
        InputStream s = p.getInputStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(s));
        String t;

        while ((t = in.readLine()) != null) {
            System.out.println(t);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您只需要这段代码:

String command = "shutdown -s -t 120 -c \"Your computer will restart. Cause something.\"";
Runtime.getRuntime().exec(command);

完美,至少在Windows系统上运行。

您的代码无效的原因是new String[]{finall, g}。如果传递数组,它将使用第一个索引作为命令,其他索引作为参数。这将导致以下内容:

Command: shutdown -s -t 120 -c
Parameter: \"Your computer will restart. Cause something.\"

相反,如果你传递一个字符串,就会发生这种情况:

Command: shutdown
Parameters: -s, -t, 120, -c, \"Your computer will restart. Cause something.\"

只能找到第二个命令,只存在独立的shutdown命令。