4 - Input and Output
4 - Input and Output
4 - Input and Output
The programmer can construct an I/O object which provides precisely the I/O
capabilities required by combining the appropriate classes handling different
aspects of the I/O process. This is done by feeding an existing stream into the
constructor of another stream to construct what is termed a filtered stream.
Java makes a clear distinction between text and binary format files. For
example, the value 12345 saved as binary is 00 00 30 39 in four byte
hexadecimal representation. Binary representation is compact and efficient but
inconvenient for human beings who prefer the representation as text
characters ‘1’ ‘2’ ‘3’ ‘4’ ‘5’ which can be conveniently read and written using a
text editor. Windows uses the one byte ASCII encoding scheme and stores
these characters in the file as 31 32 33 34 35
Java uses the two-byte Unicode encoding scheme and represents these
characters as 00 31 00 32 00 33 00 34 00 35
The Reader and Writer classes and their subclasses are provided to handle
the necessary conversions between Unicode and ASCII.
Console Input
Method 1
Console input comes from the System.in object. This object is in class
InputStream. Objects in this class can only read single bytes. This is very
inconvenient for the programmer who needs to read text characters. The
Reader subclass InputStreamReader provides this facility so we feed the
System.in object to the constructor of an InputStreamReader object:
These classes are provided in the java.io package. We want to import all the
classes in this package using the command:
import java.io.*;
import java.io.InputStreamReader;
Now object isr provides single character input. The BufferedReader class
provides I/O buffering and also useful methods as readLine(). To use these
facilities we feed the existing InputStreamReader object into the constructor
of a BufferedReader object:
import java.io.BufferedReader;
BufferedReader in = new BufferedReader(isr);
Consequently there is no end of file for console input, but if required we can enter
^Z and test the result of readLine() for null
But this is not recommended because it is useful to have objects of the separate
classes.
InputStream is = System.in;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
System.out.println(sum);
Method 2
To read console input you construct a Scanner that is attached to the “standard
input stream” System.in:
note that the Scanner class is not defined in the java.lang package but in
the java.util package so you need to use an import directive:
import java.util.Scanner;
Input dialog
To read numbers you read strings and cast them to integers or doubles using:
Integer.parseInt() and Double.parseDouble()
Again note that the JOptionPane class is not defined in the standard java.lang
package but it is defined in the javax.swing package so you need an import
directive:
System.exit();
This call terminates the thread which does not automatically terminate when the
calling program terminates.
Console Output
Sir 345456
Outputs the same string. Note that the + operator is overloaded; it means
concatenate between strings, but add between numbers, so:
The JOptionPane class has a method which allows one to display output in a
Message box as shown below:
Method 4: Console
import java.io.Console;
Method Summary
Methods
Modifier and Type Method and Description
void flush()
Flushes the console and forces any buffered output to be written immediately .
System.out.format(.....);
where format is a string that specifies the formatting to be used and args is a list of
the variables to be printed using that formatting. A simple example would be
The first parameter, format, is a format string specifying how the objects in the
second parameter, args, are to be formatted. The format string contains plain text
as well as format specifiers, which are special characters that format the
arguments of Object... args. (The notation Object... args is called varargs, which
means that the number of arguments may vary.)
Format specifiers begin with a percent sign (%) and end with a converter. The
converter is a character indicating the type of argument to be formatted. In
between the percent sign (%) and the converter you can have optional flags and
specifiers. There are many converters, flags, and specifiers, which are
documented in java.util.Formatter
int i = 461012;
System.out.format("The value of i is: %d%n", i);
The printf and format methods are overloaded. Each has a version with the
following syntax:
To print numbers in the French system (where a comma is used in place of the
decimal place in the English representation of floating point numbers), for
example, you would use:
System.out.format(Locale.FRANCE,
"The value of the float " + "variable is %f, while the " +
"value of the integer variable " + "is %d, and the string is %s%n",
floatVar, intVar, stringVar);
An Example
The following table lists some of the converters and flags that are used in the
sample program, TestFormat.java, that follows the table.
The following program shows some of the formatting that you can do with format.
The output is shown within double quotes in the embedded comment:
import java.util.Calendar;
import java.util.Locale;
double pi = Math.PI;
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c);// --> "May 29,
2006"
Note: The discussion in this section covers just the basics of the format and
printf methods. Further detail can be found in the Basic I/O section of the
Essential trail, in the "Formatting" page. Using String.format to create strings is
covered in Strings.
You can use the java.text.DecimalFormat class to control the display of leading
and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and
the decimal separator. DecimalFormat offers a great deal of flexibility in the
formatting of numbers, but it can make your code more complex.
import java.text.*;
DecimalFormat.java Output
Value Pattern Output Explanation
123456.789 ###,###.### 123,456.789 The pound sign (#) denotes a digit,
the comma is a placeholder for the
grouping separator, and the period
is a placeholder for the decimal
separator.
123456.789 ###.## 123456.79 The value has three digits to the
right of the decimal point, but the
pattern has only two. The format
method handles this by rounding up.
123.78 000000.000 000123.780 The pattern specifies leading and
trailing zeros, because the 0
character is used instead of the
pound sign (#).
12345.67 $###,###.### $12,345.67 The first character in the pattern is
the dollar sign ($). Note that it
immediately precedes the leftmost
digit in the formatted output.
Keywords in Java