首页 > 解决方案 > 如何从 Linux 上的 java 项目中的 res 文件夹运行 .sh 文件?

问题描述

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

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

但是,如何在 Linux 上运行 java 项目中 res 文件夹中的 .sh 文件?

给这个解决方案?

标签: javashell

解决方案


您可以使用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;
}

推荐阅读