【问题标题】:How to run a bat file in Startup directory with Java?如何使用 Java 在 Startup 目录中运行 bat 文件?
【发布时间】:2015-01-18 03:48:10
【问题描述】:

我尝试了以下两种方法:

Runtime.getRuntime().exec("cmd.exe /c C:/Users/USER/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/MyApp.bat");

Runtime.getRuntime().exec("cmd.exe /c \"C:/Users/USER/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/MyApp.bat\"");

它们都不起作用,第一个没有任何错误消息,第二个有以下错误消息:

java.io.IOException:无法运行程序“cmd.exe /c C:/Users/USER/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/MyApp.bat”:CreateProcess 错误=2,系统找不到java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)指定的文件

MyApp.bat 在 Startup 目录中,我可以手动运行它。

从我的 Java 应用程序运行它的正确方法是什么?

【问题讨论】:

  • 你试过用 \ 代替 / 吗?
  • `c:` 驱动器路径之前的\ 存在问题。
  • 尝试添加start关键字Runtime.getRuntime().exec("cmd /c start C:/Users/USER/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/MyApp.bat");

标签: java batch-file execute


【解决方案1】:

对于打开计算机上的任何文件 - Desktop 类非常适合。以下是它的实现方式:

import java.awt.*;
import java.io.*;
public class OpenBat {
    public static void main(String[] args) throws IOException {
        Desktop desktop = Desktop.getDesktop();
        File bat = new File("C:/Users/USER/" +
        "AppData/Roaming/Microsoft/Windows/Start " + 
        "Menu/Programs/Startup/MyApp.bat");

        desktop.open(bat);

    }
}

【讨论】:

    【解决方案2】:

    好吧,我想通了,它是:

    Runtime.getRuntime().exec("cmd /C start \"\" \"C:/Users/USER/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/MyApp.bat\"");
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2019-08-09
      • 1970-01-01
      • 2019-01-20
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多