Piyush Shrivastava
Piyush Shrivastava

Reputation: 1098

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.

Upvotes: 1

Views: 3453

Answers (4)

luboskrnac
luboskrnac

Reputation: 24581

I believe this one liner should work:

installScriptBuilder.command(new ClassPathResource("install.sh").getPath());

Upvotes: 1

dso
dso

Reputation: 109

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());

Upvotes: 2

Joop Eggen
Joop Eggen

Reputation: 109613

Resources are on the class path, typically zipped into the jar, and hence read-only, and not a File on the file system.

Use the resource as template to copy it to the file system.

Path path = dir.toPath().resolve("install.sh"); // dir a File
Path path = Paths.get(dir, "install.sh"); // dir a String
InputStream in = getClass().getResourceAsStream("/install.sh");
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);

Upvotes: 1

shankulk
shankulk

Reputation: 591

resources folder is not maintained in the target. It is maven's folder structure. You may want to take a look at target folder to understand where your install.sh file is located. It will be accessible on classpath's root.

Upvotes: 0

Related Questions