java - 通过 Java 从 Windows 命令提示符进入目录

标签 java windows cmd

通过 Java 在 Windows 命令提示符下运行某些命令时遇到了一些问题。我希望进入我的 system32 文件夹并运行某个文件,但它不会填充该命令。下面的代码段:

System.out.print("Press 1 for Normal or 2 for Keygen - " + client);
        String mode = input.nextLine().trim();
        if (mode.equals("1")) {
            String command = "cmd /c start cmd.exe";
             final String dosCommand = "cmd /c dir /s";
                final String location = "C:\\WINDOWS\\system32"; 
            Process child = Runtime.getRuntime().exec(command);
             OutputStream out = child.getOutputStream();
                out.write(dosCommand.getBytes());
                out.flush();
                out.write(location.getBytes());
                out.close();
        } else if (mode.equals("2")) {

        } else {
            System.out.println("Option not recognised");
        }

最佳答案

您似乎陷入了代码的困境。尝试使用这个:

System.out.print("Press 1 for Normal or 2 for Keygen - " + client);
String mode = input.nextLine().trim();

if (mode.equals("1")) {
    final String location = "C:\\WINDOWS\\system32";
    Runtime rt = Runtime.getRuntime();
    rt.exec("cmd.exe /c start dir /p", null, new File(location));
} else if (mode.equals("2")) {
} else {
    System.out.println("Option not recognised");
}

以下是我在自己的计算机上运行此代码片段时发生的情况:

enter image description here

如果您想运行实际的程序,只需在对 Runtime.exec() 的调用中指定即可。例如,假设您想要启动一个窗口并打印出 Java 版本。执行此操作的命令是java -version,您可以使用这行代码:

rt.exec("cmd.exe /c start cmd /k java -version", null, new File(loc));

在这里,您会注意到我在命令中添加了一个额外的 cmd/k。即使程序完成运行后,这也会使窗口保持打开状态。

关于java - 通过 Java 从 Windows 命令提示符进入目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33387924/

相关文章:

java - Spring @Resource 期望至少有 1 个有资格作为此依赖项的 Autowiring 候选者的 bean

linux - 将shell脚本转换为Windows命令行或PowerShell

windows - Git 无法在 Windows 网络环境中暂存或提交 SourceTree

windows - 针对 MONO 运行时导致 Xamarin 构建失败

Windows 批处理 : find command and errorlevel

batch-file - 检查字符串是否被引用并向字符串添加引号的问题

windows - 可以在 cmd 中启动多个命令线程吗?

java - 如何为嵌套 json 创建 JSONObject

java - 必须选择好接口(interface)名称

java - 如何格式化我的日志消息