【问题标题】:How to run .sh file from res folder in java project on linux?如何从 Linux 上的 java 项目中的 res 文件夹运行 .sh 文件?
【发布时间】:2020-07-02 14:31:49
【问题描述】:

我可以使用此代码从 java 项目中的 res 文件夹中访问图像。

MyClass.class.getResource("/Images/main.jpg");

但是,我怎样才能在linux上的java项目的res文件夹中运行.sh文件呢?

给这个解决方案?

【问题讨论】:

  • 听起来很粗略,你想达到什么目的?
  • 我想在 linux os 上运行项目 res 文件夹中的 .sh 文件。

标签: java shell


【解决方案1】:

您可以使用Runtime.exec()

public static void excuteCommand(String filePath) throws IOException{
    File file = new File(filePath);
    if(!file.isFile()){
        throw new IllegalArgumentException("The file " + filePath + " does not exist");
    }
    if(isLinux()){
        Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", filePath}, null);
    }else if(isWindows()){
        Runtime.getRuntime().exec("cmd /c start " + filePath);
    }
}

public static boolean isLinux(){
    String os = System.getProperty("os.name");  
    return os.toLowerCase().indexOf("linux") >= 0;
}

public static boolean isWindows(){
    String os = System.getProperty("os.name");
    return os.toLowerCase().indexOf("windows") >= 0;
}

【讨论】:

  • @Pradeep 使用您的 .sh 文件路径调用 excuteCommand,它将运行它
  • @Pradeep ex。你把你的 .sh 文件放在 /image/mysh.sh 中,然后调用 excuteCommand("/image/mysh.sh")
  • 我可以在 linux 和 windows 上运行 .sh 文件吗?
  • @Pradeep 你可以,这段代码会在windows中调用cmd来运行你的.sh,它会在linux中调用sh来运行你的.sh,只要确保你的文件路径。
猜你喜欢
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
  • 2013-03-03
  • 2012-03-07
  • 2012-12-19
  • 1970-01-01
相关资源
最近更新 更多