location of shell script called from java application
I have a java application from which i am calling a shell script. Can any one tell where to keep the script file in my application and what is the path to access the file in whole application.
i m keeping my script in the java package but when i m trying to access using path like com.abc.script.sh by running my java application through unix i ma getting error java.io.IOException: error=2, No such file or directory
i am calling 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 am running the application from uni开发者_C百科x.
i need to pass the parameter to shell script file as well . the parameters are like hostname , table name...
where to keep the script file in my application
Your wrote, I can interprete this like:
- Storing the content of the file into the memory
- Storing the file into your
.jar
file
I think you mean the second.
You can place it in your jar file in every folder you want. I prefer a subfolder (not the root)
First put the file in your jar. Then you have to extract it to a temporary file (See the link if you want to know how to make a tempfile).
Then create an inputstream from the file in your jar and copy the data to the 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 have to execute your shellscript
Runtime.getRuntime().exec("terminalname " + tempFile.getAbsolutePath());
Maybe you can use this line to execute your script (I don't think this will work with your parameters):
java.awt.Desktop.getDestkop().open(tempFile);
I hope this is an answer for your question.
You could store your shell script as a resource (e.g. inside your jar file), then exec a shell and pipe the content of your script as standard input to the running shell.
Something like this (haven't tried it):
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 );
If you happen to be using the Spring framework for this project, a good and simple option is to store the shell script in a folder on your class path and use a ClassPathResource object to locate it.
精彩评论