Search code examples
javaspringspring-bootprocessbuilder

ProcessBuilder cannot find sh file in resources folder - Spring Boot


I have searched for a solution for a while on the internet but none give a clear image of how the sh file will be executed.

I have a shell script install.sh which I have kept in the resources directory. I want to run this from ProcessBuilder. No matter what I try, I keep getting a No such file or directory error. This is my code:

String masterURL = config.getMasterUrl();
String adminToken = config.getAdminToken();

ProcessBuilder installScriptBuilder = new ProcessBuilder();
installScriptBuilder.command("install.sh", dir, namespace);
installScriptBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

Map<String,String> installEnv = installScriptBuilder.environment();
installEnv.put("URL", masterURL);
installEnv.put("TOKEN", adminToken);

try {
    Process p = installScriptBuilder.start();
} catch (IOException e) {
    e.printStackTrace();
}

I have read about creating a temporary file in other answers but none clearly show how to solve this problem with that. I have used Spring Initializr for creating my project.


Solution

  • You can select resource files with "classpath:install.sh".

    In this case we can´t do that. We need the path itself:

    final ClassLoader classLoader = getClass().getClassLoader();
        final File file = new File(classLoader.getResource("install.sh").getFile());
        final ProcessBuilder installScriptBuilder = new ProcessBuilder();
        installScriptBuilder.command(file.getPath());