I have to write two scripts, one to compile my code and another one to run it. I manage to compile the code with this script:
#!/bin/bash
javac SimilaridadeP.java
And I was able to run it using this script:
#!/bin/bash
java SimilaridadeP
The problem is that I need to execute my second shell script following this command:
./execute.sh input output
Where input and output are the names of the files that I am going to use in my Java code. The problem that I am facing right now is that I don't know how I can use these both names in my Java code.
So far I managed to get both names using this code:
#!/bin/bash
in=$1
out=$2
java SimilaridadeP
But since "SimilaridadeP" is the name of my java file and it can't be called like a method with parameters I am kind of lost.
If your java code is already reading the command-line parameters, it's just a matter of changing the bash this way:
#!/bin/bash
java SimilaridadeP "$1" "$2"
This works with arbitrary number of arguments:
#!/bin/bash
java SimilaridadeP "$#"
Related
I am trying to create to create a script that will automatically change the working directory to my Java code and then compile the code. I am able to change the directly to my path but I cannot figure out how to to call the java compiler on the "filename" while taking the "filename" as an argument directly from the Terminal.
#!/bin/bash
FILE = “$1”
open -a Terminal /Users/Jarvis/Desktop/Codes/Java/CS\ 49J/
javac “$FILE”
Remove the spaces in your FILE assignment. Also, as #cricket_007 mentions, you don't need to open the terminal app, just change directory.
#!/bin/bash
FILE="$1"
cd /Users/Jarvis/Desktop/Codes/Java/CS\ 49J/
javac "$FILE"
Alternatively (I'm in the habit of using curly braces around variables):
#!/bin/bash
FILE="$1"
WORKING_DIR="/Users/Jarvis/Desktop/Codes/Java/CS\ 49J/"
javac "${WORKING_DIR}${FILE}"
I have created one java program on my Linux system which indents and formats the given file. I want to make that program work like a command in Linux which will take file names and other options as arguments and then will produce the output. I can do this with a C program by just copying the compiled executable in /bin folder but I don't know how to do it with java.
Sample script that can might further help-
#!/bin/bash
#Set whatever number of arguments you expect for the Java jar you have
ARGS_EXPECTED=3
if [ $# -ne $ARGS_EXPECTED ]
then
echo "[$HOSTNAME]: Usage: `basename $0` filename arg1 arg2"
exit 1
fi
java -cp yourfile.jar com.yourpkg.Driver $1 $2 $3
Save the above content to a file, say test.sh
and use the command to give an executable permission chmod +x test.sh
run like ./test.sh filename arg1 arg2 from current directory where test.sh is
I thing this can be useful for your case: http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/binfmt_misc.txt?id=HEAD
You can simply run a Java class file or jar file with "java" command from command line. Example:
java -jar yourprogram.jar argument1 argument2
If you save this line in a text file saved for example as "script.sh" and then give it the permission for execution you can run it double clicking or from terminal typing ./script.sh in the same folder containing the file script.sh.
You can also produce scripts that use arguments with $1 $2 etc. avoiding the need of editing file.
http://www.linuxquestions.org/questions/linux-newbie-8/how-to-pass-command-line-parameter-to-shell-script-254396/
You can use named parameters, too.
You can also produce a C program for a new command like you suggested that run the "java" command. In this case you can introduce arguments directly from terminal and pass them to java command in the C source.
As others have pointed out it is probably best to use a small shell script to run the Java application. There are several open source products that will help you wrap your Java code to produce a runnable (set of) .jar(s).
If you have correctly separated your business logic from your interface (as you should) then it is probably best if your Java application parses the parameters given on the command line interface. To do this create a separate class for parsing such parameters and calling the classes making up the business logic. Of course this will lead quickly - if not immediately - in writing a parser for Linux like CLI parameters. When this happens you may wish to consider the Apache Commons CLI project.
If you don't want to use any wrapping application/runtime, my method is generally pointing to all the class file containers in the classpath and directly pointing to the class containing the static main method:
java -cp "path_to_jar;path_to_class_folder;etc" "nl.owlstead.stackoverflow.LinuxMain"
The following doesn't work in Java (an exception is thrown):
Runtime.getRuntime().exec("cd mydir; myprog");
The same works fine in PHP:
exec("cd mydir; myprog");
What exactly is different in Java's implementation and why (it seems more limited at first glance)?
the java exec command does not use the system command interpreter. something like "cd mydir; myprog" depends on the system command line interpreter (e.g. on windows cmd, on linux sh) to split that into 2 separate commands and execute each of them. java does not invoke the system command interpreter, so that does not work. you either need to call each command separately, or invoke the desired interpreter yourself as part of the command line.
I've seen people have problems like this, and I'm sure there are several ways, however the one I've seen most people reply is this. add cmd before it.
Runtime.getRuntime().exec("cmd cd mydir; myprog");
Assuming you're running an applet, not Java in a CLI environment on the server? If so, then your Java runtime is running on the client computer, not the server.
Java also has a better way to handle multiple commands than your semicolon. Instead of using the signature:
Runtime.exec(String)
try using this for each of your commands:
Runtime.exec(String[])
and make each argument of your command an element in the String array.
I am trying to finish a java program that uploads a file from a client machine to a webserver. The java program is executed with a bat script. I need to pass in a file name to the java program somehow since the filename is different every time. Or can i somehow use %1 instead of the filepath? I dont know.
Why not simply forward the parameters passed to the shell script to the Java application. I usually do something like this:
#!/bin/zsh
java -jar someapp.jar $#
This will pass all the arguments with which the script was executed to the java app and you can act upon them - as far as I understand you need only only - the file path. I'm not familiar with bat scripts, but I assume they have some similar way of passing args around.
What does the batch file look like that runs the Java program? You can indeed use parameters like this:
java -jar program.jar %1
If you put that line in a file runprogram.bat, then you could run it with:
runprogram somefilename.xyz
and somefilename.xyz will be passed to the Java program as a command line argument.
No they got it, if i could just pass the filepath as a parameter to the executed jar that would be awesome. Just need to figure out how to pass that parameter into a variable in the program....
This question already has answers here:
How do I auto load a database jar in Groovy without using the -cp switch?
(5 answers)
Closed 6 years ago.
I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy at the top of my script.
Starting a groovy script with #!/usr/bin/env groovy has a very important limitation - No additional arguments can be added. No classpath can be configured, no running groovy with defines or in debug. This is not a groovy issue, but a limitation in how the shebang (#!) works - all additional arguments are treated as single argument so #!/usr/bin/env groovy -d is telling /usr/bin/env to run the command groovy -d rathen then groovy with an argument of d.
There is a workaround for the issue, which involves bootstrapping groovy with bash in the groovy script.
#!/bin/bash
//usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $#; exit $?
import org.springframework.class.from.jar
//other groovy code
println 'Hello'
All the magic happens in the first two lines. The first line tells us that this is a bash script. bash starts running and sees the first line. In bash # is for comments and // is collapsed to / which is the root directory. So bash will run /usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $# which starts groovy with all our desired arguments. The "$0" is the path to our script, and $# are the arguments. Now groovy runs and it ignores the first two lines and sees our groovy script and then exits back to bash. bash then exits (exit $?1) with status code from groovy.
If you really have to you can also load a JAR at runtime with:
this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())
My Favorite way to do this is with Groovy Grapes. These access the Maven Central Repository, download the referenced jar, and then put it on the classpath. Then you can use the library like any other library. The syntax is really simple:
#Grab(group='com.google.collections', module='google-collections', version='1.0')
You can read more details here. One major advantage here is that you don't need to distribute your dependencies when you distribute your script. The only drawback to this method is that the Jar has to be in the Maven repository.
You can add the jars to $HOME/.groovy/lib
You can also try out Groovy Grape. It lets you use annotations to modify the classpath. Its experimental right now, but pretty cool. See docs.groovy-lang.org/.../grape
The same as you would in Java.
This is an example of running a MySQL status monitoring script. mysql.jar contains the MySQL connector that I call from script status.groovy.
groovy -cp mysql.jar status.groovy ct1
Below is a combination of Patrick's solution, Maarteen Boekhold's solution, and foozbar's comment that works with both Linux and Cygwin:
#!/bin/bash
// 2>/dev/null; SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
// 2>/dev/null; OPTS="-cp $SCRIPT_DIR/lib/extra.jar:$SCRIPT_DIR/lib/spring.jar"
// 2>/dev/null; OPTS="$OPTS -d"
// 2>/dev/null; OPTS="$OPTS -Dlog4j.configuration=file:/etc/myapp/log4j.xml"
// 2>/dev/null; exec groovy $OPTS "$0" "$#"; exit $?
import org.springframework.class.from.jar
//other groovy code
println 'Hello'
How it works:
// is a valid groovy comment, so all of the bash commands are ignored by Groovy.
// will return an error, but the error output is redirected to /dev/null and is therefore not displayed.
bash executes commands following a semicolon even though the previous command failed.
exec replaces the current program in the current process without forking a new process. Thus, groovy runs within the original script process (ps shows the process as the script rather than the groovy executable)
The exit $? statement following exec groovy prevents bash from trying to interpret the rest of the script as a bash script, and also preserves the return code from the groovy script.
The above bash trick is more convenient in some cases than the RootLoader trick because you can use regular import statements within the script. Using the RootLoader trick forces you to load all of the classes using reflection. This is fine in some situations (such as when you need to load a JDBC driver), but inconvenient in others.
If you know your script will never be executed on Cygwin, then using Patrick's or Maarteen's solution will likely result in slightly better performance because they avoid the overhead of generating and throwing away an error.
Adding to #Patrick his answer, which helped me a lot, I recently discovered another trick.
If you add lots of jars to the classpath all on one line, things can become quite unreadable. But you can do the following!
#!/bin/bash
//bin/true && OPTS="-cp blah.jar -Dmyopt=value"
//bin/true && OPTS="$OPTS -Dmoreopts=value2"
//usr/bin/env groovy $OPTS "$0" $#; exit $?
println "inside my groovy script"
Let your imagination run wild on how complex a command line you can break down this way into manageable pieces
Maarten
If you want to use it right away before the import declarations it is possible like this :) :
// printEmployees.groovy
this.class.classLoader.rootLoader.addURL(
new URL("file:///C:/app/Dustin/product/11.1.0/db_1/jdbc/lib/ojdbc6.jar"))
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:#localhost:1521:orcl", "hr", "hr",
"oracle.jdbc.pool.OracleDataSource")
sql.eachRow("SELECT employee_id, last_name, first_name FROM employees")
{
println "The employee's name is ${it.first_name} ${it.last_name}."
}
Taken from this javaworld.com article.