Reputation: 475
Hi i am using this code to run the shell script.the thing is i want to pass argument "trng-java" while i am running program.like this
like java Classname trng-java
code:
import java.io.*;
public class Test
{
public static void main(String[] args)
{
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/bin/sh", "/tmp/test.sh", "trng-java"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
How to do this?
Upvotes: 0
Views: 1428
Reputation: 25725
When you pass arguments to a java application, they are accessible through the args[]
array in main.
See: http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html which I am quoting:
Echoing Command-Line Arguments
The Echo example displays each of its command-line arguments on a line by itself:
public class Echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } }
The following example shows how a user might run Echo. User input is in italics.
java Echo Drink Hot Java Drink Hot Java
Parsing Numeric Command-Line Arguments
If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to an int:
int firstArg; if (args.length > 0) { try { firstArg = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + " must be an integer"); System.exit(1); } }
Upvotes: 2
Reputation: 2563
Process pr = rt.exec(new String[]{"/bin/sh", "/tmp/test.sh", args[0]});
Of course, you will also need to check that args contains at least one argument
Upvotes: 2
Reputation: 54672
in public static void main(String[] args)
the args parameter is the arguement. If you use multiple arguement like
java Classname a b c
Then in your main method args will be an array containing a,b,c
if this is what you want then args[0]
is the preferred arguement.
Upvotes: 0
Reputation: 850
Command line arguments are passed to your application in the String[] parameter args, so you should be able to access the value using args[0]
.
Process pr = rt.exec(new String[]{"/bin/sh", "/tmp/test.sh", args[0] });
Upvotes: 3
Reputation: 3260
Just add the argument(s) to your command, like this:
rt.exec("/bin/sh /tmp/test.sh trng-java");
Upvotes: 0
Reputation: 749
The argument you pass in will be found in the args parameters as String yourParam = args[0]
Upvotes: 5