简体   繁体   中英

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.

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

我相信这一班轮应该行得通:

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM