Java Reference
In-Depth Information
1.8.3 File redirections
Instead of writing messages to the console, one can redirect them to a text file
without changing the source code, using the > symbol in the command line.
For example consider the following toy program, which asks for an integer and
squares it:
import java . util . ;
class SmallProg {
public static void main( String [ ] args )
Scanner keyboard= new Scanner(System . in ) ;
int val ;
System . out . print ( "Enter an integer please:" );
val=keyboard . nextInt () ;
val =val ; // squared the input value
System . out . println ( "Squared value=" +val ) ;
}
}
Running the program from the console, we get:
prompt%java SmallProg
Enter an integer please:5
Squared value=25
Let us now store the output message into a text filename output.txt .Wehave
prompt%java SmallProg >output.txt
4
The above number 4 is the number input by the user when running the program.
Let us inspect the file named output.txt by opening it:
Enter an integer please:Squared value=16
Thus all messages printed out using the instruction System.out.print[ln ] have
been redirected to filename output.txt . Similarly, we can set the input of a
program from a filename by redirecting the input from the command line using
the symbol < . Let us create a file input.txt containing the (string) value 4.
We can now execute the program by redirecting its input as follows:
prompt%java SmallProg <input.txt
Enter an integer please:Squared value=16
... or redirect both input/output:
prompt%java SmallProg <input.txt >output.txt
This will overwrite the former output file output.txt .
 
Search WWH ::




Custom Search