I am writing a program that takes one action if the command line contains a stream redirection, such as > or <, but takes another action otherwise.
My first instinct was to loop through the command line and check if each argument equals the redirection symbol, like this:
public boolean hasRedirection(String[] args){
boolean flag = false;
int length = args.length;
int i;
for(i = 0; i < length; i++){
System.out.println(args[i]);
if(args[i].equals(">") || args[i].equals("<"))
flag = true;
}
return flag;
}
However, it always returns false. The line System.out.println(args[i]); shows that any redirection and subsequent filename are not being recognized. For example:
project\src>java myProgram.Client localhost 1234 > myFile.txt
localhost
1234
whereas it should be:
project\src>java myProgram.Client localhost 1234 > myFile.txt
localhost
1234
>
myFile.txt
Is there a simpler way I can do this? Thanks for your time!
The redirection is part of the shell’s syntax, not something passed along to the program. Instead, check whether
System.console()returns a non-null value.