I/O from the Command Line
A program is often run from the command line and interacts with the user in the command line environment. In Java, this feature is supported in 2 ways, through the Standard Streams and through the ConsoleStandard Streams
Java supports three standard streams, namely System.in, System.out & System.err. These objects are defined automatically and do not need to be opened. Standard Output and Standard Error are both for output; having error output separately allows the user to divert regular output to a file and still be able to read error messages. System.out and Stystem.err are defined as PrintStream objects. System.in is sub-type of byte stream. To use it for character input, it has to be wrapped with InputStreamReader as follows:InputStreamReader cin = new InputStreamReader(System.in);
The Console
Console is more advanced than Standard Streams. It is particularly useful for secure password entry, which is implemented using the readPassword method. The Console object also provides input and output streams through its reader and writer methods.Inorder to use Console, its object must be invoked using System.console(). If the object is available, then this method returns it else a NULL is returned. Non-availability might be because OS doesn't support or because the program was launched in a noninteractive environment.
Data Streams
Data streams support binary I/O of primitive data type values as well as String values. All data streams implement either the DataInput interface or the DataOutput interface. DataInputStream and DataOutputStream are the most widely used implementations of these interfaces. DataStreams can only be created as a wrapper for an existing byte stream object:out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));. Some methods used in DataStreams are:
in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
writeDouble(double);It is important that a data stored with a particular write method, should be read with the corresponding read method. It is up to the programmer to make sure that output types and input types are matched in this way.
writeInt(int);
writeUTF(string);
readDouble();
readInt();
readUTF();
No comments:
Post a Comment