Script shell location invoked from a Java application

I have a Java application from which I call a shell script. Can anyone tell me where to store the script file in my application and what is the path to access the file in the whole application.

im saving my script in a java package, but when I try to access using a path like com.abc.script.sh, running the java application through unix I ma, getting the error java.io.IOException: error = 2, There is no such file or catalog

I call the script file with some argument with the following code

private static final String command = "com.abc.script.sh -db abc -scm TEST_xyz -bcp com.abc.out.txt -log / var / tmp -tab abc_ $ TABLENAME";

Process process = Runtime.getRuntime (). exec (command);

and I run the application from unix.

I need to pass this parameter to a shell script file. parameters are similar to host name, table name ...

+4
source share
3 answers

where to store the script file in my application

Your wrote, I can interpret this as:

  • Storing file contents in memory
  • Saving a file in a .jar file

I think you mean the second.

You can put it in your jar file in every folder you need. I prefer a subfolder (rather than a root)

First put the file in your jar. Then you have to extract it to a temporary file (see Link if you want to know how to create a temporary file).
Then create an input stream from a file in your bank and copy the data to a temp file.

 InputStream is = getClass().getResourceAsStream("/path/script.sh"); OutputStream os = new FileOutputStream(tempFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } buffer = null; // Clear the buffer 

Then you must execute your shellscript

 Runtime.getRuntime().exec("terminalname " + tempFile.getAbsolutePath()); 

Perhaps you can use this line to execute the script (I don't think this will work with your parameters):

 java.awt.Desktop.getDestkop().open(tempFile); 

Hope this answers your question.

+3
source

You can save your shell script as a resource (for example, inside your jar file), then execute the shell and pass the contents of your script as standard input to the current shell.

Something like this (not tried):

 ProcessBuilder processBuilder = new ProcessBuilder( "/usr/bin/bash" ); Process process = processBuilder.start(); OutputStream outputStream = process.getOutputStream(); InputStream resourceStream = getClass().getResourceAsStream( "/path/to/my/script.sh" ); IOUtils.copy( resourceStream, outputStream ); 
0
source

If you use the Spring framework for this project, a good and easy option is to save the shell script in a folder in your class path and use the ClassPathResource object to find it.

0
source

All Articles