Hi all! I have written this program for reading command line arguments.
public class UseArgument {
public static void main(String args[])
{
System.out.print("hi, ");
System.out.print(args[0]);
System.out.println(" How are you?");
}
}
I tried to send the following argument through the command line:
java UseArgument #!&^%
and it's throwing an error as follows.
Output:
hi, #! How are you?
''%'' is not recognized as an internal or external command,
operable program or batch file.
java UseArgument #!^%
Can anybody explain this behavior? Does this relate to regular expressions?
Thanks.
sivakiran B
Some of the special characters you are using have a meaning to the shell from which you are launching your program. By putting the characters in quotes, you are instructing the shell not to process these characters according to their special meaning.
Related
I have pretty simple wrapper script which aquires parameters and passes them to java jar.
Unfortunatly, I experience very-very strange behaviour. Below is an example.
Command to execute script:
./wrapper http://localhost:8485/metrics 900 200
Script:
#/bin/sh
/usr/java/default/bin/java -jar /usr/plugins/checkmetrics.jar $#
Java code:
public static void main(String[] args) throws IOException {
String metricsUrl = args[0];
int heapWarnValue = Integer.parseInt(args[1]);
int threadWarnValue = Integer.parseInt(args[2]);
}
Which gives me NumberFormatException:
"xception in thread "main" java.lang.NumberFormatException: For input string: "200
But if I change command to following, everything works:
./wrapper http://localhost:8485/metrics 900 200" "
Breaks my brain, but I can't understand where I'm wrong. Could someone explain?
Thanks in advance
Is there an LF or CR character at the end of the script that is not being correctly processed (could happen if you have unix line endings in a windows environment or vice versa)?
the reason I mention this is that the error you mention says that it is
For input string: "200
I'm willing to bet that there is another quote mark at the start of the next line. If that's the case, it's trying to parse 200 and CR together as an integer. Sort out the line endings and all will be fine.
I am new to programming, but I am coming along. I am using the online IDE written in php from www.compilejava.net. My question is this. I tried to use this code and I took it directly out of a Java textbook:
class DollarArguement {
public static void main(String args[]) {
for(int i=0;i<args.length; i++) {
if(args[i].startsWith("$")) {
System.out.print(args[i]);
break;
}
}
}
}
It works for every character I have tried except "$". I would like to put multiple strings in the commandline and search for $ values. Does anyone know why this is not working? Thanks in advance.
I tested your code on OSX and it displayed no results for "$", but if i changed it to "." it printed the first result (because of the break statement).
The reason is that on OSX (and other Unix systems) the bash terminal is looking for values which start with $ as these signify variable names.
you can test this simply by typing in a terminal
echo Hi
Hi
echo $Hi
(no result)
I assume the strings with the $ prefix are never evening making it into the program.
You can escape the $ with a backslash. Try running your program with these backslashes in your parameters.
echo \$Hi
$Hi
eg.
java -cp . DollarArguement \$test
$test
I am wondering how I can read the starting line from the command prompt in Java.
For example if you run a Java program namned Test.java I usually writes:
java Test
, But if I write this in the command prompt(see below), I would like to read the "string" in the test.java-file when it starts:
java Test string
how can I in the test.java file get access of the string "string"?
I have tried:
Scanner in = new Scanner (System.in);
String text= in.nextLine();
but that only allows me to get access of the next thing that is written in the command prompt.
To read command line parameters you should use the String[] args argument of the main method not read from standard in.
if you are inside main method then you can simply do as
public static void main(String[] args) {
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
because args will have all the command line arguments values after java <class name> command
I am guessing that Test class has a main method...
public static void main(String[] args) { ... }
The array passed in to main contains the arguments you pass on the command line...
args[0].equals("string") == true
Or do you want to get the entire command line that started the JVM?
The command line arguments show up in the args[] array that is passed to the main method. So to get the name of the file that was passed on the command line, you can just look at args[0]:
System.out.println(args[0]);
public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Scanner read becomes active when any inputs provided once java program started because of this reason it did not read the command prompt input but it is able to read next line to the command prompt. It did not bother the past input or input provide before scanner class comes into action what it cares the values provided once Scanner class in action.
This question already has answers here:
System.console() returns null
(13 answers)
Closed 8 years ago.
I am working on a legacy app which depends on user command line input:
String key = System.console().readLine("Please enter the license key: ");
However, I am getting a NullPointerException because System.console() gives me a null.
Why does System.console() return null for a command line app? It happens when running it out of the terminal as well as IDE.
If you start java from a terminal window, then it really should work, even though I haven't tried on OSX.
If you run a simple test using java directly from the terminal, does it work?
echo 'public class Test { public static void main(String[] args) {System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test
Expected output:
hello world
If it doesn't work, then sorry, no console support on your platform.
However, if it works, and your program doesn't then there is a problem with how your program is started.
Check how the java binary started? Is it started from a shell script? Check that stdin/stdout have not been redirected or piped into something, and possibly also that it's not started in the background.
ex: This will probably make System.console() return null.
java Test | tee >app.log
and this:
java Test >/tmp/test.log
This seems to work on my machine (linux)
java Test &
Neither does it seem as if System.setOut, System.setErr or System.setIn affects the console, even after a couple of gc's and finalizers.
However:
Closing (the original) System.out or System.in will disable the console too.
echo 'public class Test { public static void main(String[] args) {System.out.close();System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test
Expected output:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:1)
So; scan your code for places where it closes streams, or passes System.out somewhere it might get closed.
To read from Standard input (command line input) you must use some kind of stream reader to read the System.in stream.
An InputStreamReader initialised by
InputStreamReader(System.in)
lets you read character by character.
However, I suggest wrapping this with a BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = reader.readLine();
Must import
java.io.*;
The code given below actually tries running a command. This command when run from command prompt, produces the necessary output. But when i try to run the application from java code, it keeps on running and doesn't produce any output file.
String arg[]={"C:\\app1.exe", "C:\\app2.exe", "c:\\app3.exe"};
String pwd[]={"123","-x","-sf"};
String outputfile="c:\\output.xml"
String command=arg[0]+pwd[0]+arg[1]+pwd[1]+arg[2]+pwd[2]+output;
Process pr=rt.exec(command);
String command=arg[0]+pwd[0]+arg[1]+pwd[1]+arg[2]+pwd[3]+output;
At least you are missing the whitespace between the arguments!
You should not concatenate all arguments to one string. Instead, pass them as separate arguments to
Process exec(java.lang.String[])
I think you made mistake in generating command.
It would be
C:\\app1.exe123C:\\app2.exe-xc:\\app3.exe-sfc:\\output.xml
Make sure the space
And use this exec(String[]
My guess is that you haven't tried this in a debugger or printed what it is trying to run.
My guess is that when you make this compile, you don't have a command called.
C:\app1.exe123C:\app2.exe-xc:\app3.exe-sfc:\output.xml
You cannot have more than one : in the path.
You concatenate all commands and args, but you never insert spaces between the commands and args.
So your command looks like this: "C:\app1.exe123C:\app2.exe-xc:\app3.exe-sfc:\output.xml"
And also pwd[3] doesn't exist. You have an array with 3 elements, so the highest element would be pwd[2]. You should get and ArrayIndexOutOfBoundsException here (or is it just a copy-paste-mistake)?
Well there's a couple of things wrong with the code:
A space is needed between the commands and the arguments and pwd[3] is out of bounds. I ran this code and it works.
String arg[]={"C:\\app1.exe", "C:\\app2.exe", "c:\\app3.exe"};
String pwd[]={" 123"," -x"," -sf"};
String outputfile="c:\\output.xml";
String command=arg[0]+pwd[0]+arg[1]+pwd[1]+arg[2]+pwd[2]+outputfile;
try {
Process pr=Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
Try:
String[] command = new String[] { arg[0], pwd[0], arg[1], pwd[1],
arg[2], pwd[2], output };
This is assuming the command you wish to run is
C:\app1.exe 123 C:\app2.exe -x C:\app3.exe -sf c:\output.xml
If you really want to run three separate commands, you will have to run exec() more than once.
See the javadoc at http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String[]) for details.
EDIT: As another answerer has pointed out, there is no pwd[3]!
If your apps "app1", "app2" ... are run from the command prompt you need open that before.
by launching cmd.exe first of all.
And then as others suggested add space between app and arguments.
Try by pasting this in the Run/Search input field in windows:
cmd.exe /K C:\app1.exe 123 C:\app2.exe
-x c:\app3.exe -sf c:\output.xml
cmd.exe /K keeps the propmt open after executing commands