FORMATTING AND INPUT/OUTPUT
METHODS
Lesson 4
Objectives
To learn ways to input data and output results in java
By the end of this chapter Students should be able to
i. Use interactive input method to read values into a
program.
ii. Use specific format to read or write data.
iii. Instruct the program to read data from or write output
to a file.
Input and Output Statement
Java just like other programming languages have the opportunity to either
read from the keyboard values that will be assigned to variables declared in a
program or to read from an input file also output can be written directly on to
the screen or into a file. The major difference between Java and other
programming languages is that while other programming languages use
objects or statement to achieve this, Java makes use of methods and objects
instantiated from a class. In java input can be read using interactive Scanner
Object or graphical JOptionPane objects.
Interactive Input Using a Scanner Object
A scanner object can be used for interactive input. One scanner
object can be used for an unlimited number of input values.
Scanner is a predefined class in Java that is found in one of the
predefined packages in Java called the [Link] package.
>> Discuss the JOptionPane Object from
[Link] class.
Before using a scanner object for input, the following has to be
done:
- Include the import declaration statement:
import [Link].*;
(Note: This import statement calls all the classes found in
the utility package). To safe program execution time, the
Scanner class should be called directly or explicitly
imported from the utility class as shown below;
import [Link];
- Declare a scanner object with the statement:
Scanner name = new Scanner ([Link]);
where name is a valid Java identifier (e.g. input,
keyboard, sc, bag etc.) once a scanner has been declared,
we can use the following methods to read data:
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
where name is the declared object of the scanner class.
Class Activity
Write a simple calculator program to illustrate interactive
input using Scanner object and JOptionPane object.
Hint: Add two double or floating point variables together
and output the result.
// A simple java code to test input
import [Link];
Public class SimpleCal{
public static void main(String args[]){
double a;
double b;
double sum;
Scanner jerry = new Scanner([Link]);
[Link](“Enter value for a: \n”);
a = [Link]();
[Link](“Enter value for b: \n”);
b = [Link]();
sum = a + b;
[Link](FormatString, “Sum is: “+ sum + “\n”);
}
}
Formatting Output (print(), println(), printf())
So far the methods print() and println() have been considered and
used to demonstrate output method procedures. However, they
both cannot directly format certain outputs in a specific manner.
To format the output in a specific manner we use the method
printf( ).
The method printf( ) formats and output data to the standard
output stream, [Link].
The syntax to use the method printf( ) to produce output on the standard
output device is:
[Link] (format String);
Or
[Link] (formatString, argument);
where formatString is a string specifying the format of the output and
argumentList is a list of arguments, that consist of constants, values,
variables and expression. If argumentList has more than one argument,
then the argument, are separated with commas.
Examples of Format Using Printf( )
int num = 96;
double rate = 20.50;
Consider the following output statements:
(a) [Link] (“12345678912345”);
(b) [Link] (“ %5d\n”, num);
(c) [Link] (“ %5.2 f\n, rate);
(d) [Link] (“ % 5d%6.2f\n”, num, rate);
The output of the above statements would be:
(a) 123456789012345
(b) 96 (output in 5 columns, right justified);
(c) 20.50(output in 5 columns with two decimal places, the decimal place requires a column. The
width specifier for floating point value include a column for decimal point)
(d) _ _ _96_ 20.50: (output of num is in 5 columns followed by the value of rate in 6 columns
with 2 decimal places, starting in column 6.
What will be the output of
[Link](“%1$tz %1$tI: %1$tM: %1$tS: %tP”, datetime);?
JAVA FILE INPUT/OUTPUT
Introduction
● Data stored in a text file is represented in
human-readable form.
● Data stored in a binary file is represented in
binary form.
● Binary files cannot be read. They are designed
to be read by programs.
● For example, Java source programs are stored
in text files and can be read by a text editor, but
Java classes are stored in binary files and are
read by the JVM.
● Advantage of binary files is that they are more
efficient to process than text files.
Introduction (cont.)
▶ You can imagine a text file as consisting of a
sequence of characters and a binary file as
consisting of a sequence of bits.
▶ For example, the decimal integer 199 is stored as
the sequence of three characters, “1‟, “9‟, “9‟ in a
text file, and the same integer is stored as a
byte-type value C7 in a binary file
(hex , 199=12x161+7)
How is I/O handled in Java
▶ To perform I/O, you need to create objects using
appropriate Java I/O classes.
▶ The object contain the methods for reading/writing
data from/to a file.
▶ There are many I/O classes for various purposes.
These can be classified as input classes and
output classes.
▶ An input class contains the methods to read data,
and an output class contains the methods to write
data
MAJOR TYPES OF FILE I/O
▶ Computers do not differentiate binary files and text
files. All files are stored in binary format
▶ Text files
❖ A sequence of characters
❖ Easy for reading, modifying & writing a text file
using a text editor
▶ Binary files
❖ A sequence of bits –data items consists of
usually 8bit bytes
❖ More compact
❖ More efficient
Text I/O vs. Binary I/O
▶ Text I/O
❖ Text I/O is built upon binary I/O to provide a level
of abstraction for character encoding and
decoding.
❖ Encoding and decoding are automatically
performed for text I/O.
❖ The JVM converts a Unicode to a file-specific
encoding when writing a character and converts a
file-specific encoding to a Unicode when reading a
character.
Text I/O vs. Binary I/O (cont.)
▶ Binary I/O
❖ Binary I/O doest not require conversions.
❖ If you write a numeric value to a file using binary I/O, the
exact value in the memory is copied into the file.
❖ When you read a byte using binary I/O, one byte value
is read from the input.
❖ In general, use text input to read a file created by a text
editor or a text output program, and use binary input to
read a file created by a Java binary output program.
Text I/O vs. Binary I/O (cont.)
▶ Binary I/O is more efficient than text I/O, because binary
I/O does not require encoding and decoding.
▶ Binary files are independent of the encoding scheme on
the host machine and thus are portable.
▶ Java programs on any machine can read a binary file
created by a Java program.
Text I/O vs. Binary I/O (cont.)
JAVA FILE I/O
▶ I/O classes are listed in [Link] package
▶ For Java 5.0, the Scanner class can be used for text input
▶ Text files
❖ Known as character stream i/o. use 16 bit Unicode
characters, making them platform independent. Use
Reader and Writer classes and their subclasses
▶ Binary files
❖ Known as byte stream i/o. use 8 bit bytes, platform
dependent. Use Input Stream and Output Stream classes
and their subclasses.
JAVA TEXT FILE CLASSES & METHODS (cont.)
▶ Relevant java text i/o classes
▶ Basics
❖ Create a File object and associated it to the file
➢ File inFile = new File(“[Link]”) -locate the file in
the current directory
❖ Specify the path and file or directory name when call the
constructor
➢ File inFile = newFile(“C:\\JavaProg”,[Link]”); or
➢ File inFile = newFile(“C:\\JavaProg\\[Link]”); or
➢ File inFile = newFile(“C:\\JavaProg\\fileio”);
JAVA TEXT FILE CLASSES & METHODS
INPUT
▶ Classes
1. File – encapsulates the properties of a file or a path &
does not contain methods to read/writing data from/to a file
2. FileReader – convenience class for reading character files
3. BufferedReader –read text from a character input stream
▶ Methods
1. readLine() –read a string line; return a String
2. read() –read a single character; eof is -1
3. close() –close input stream
JAVA TEXT FILE CLASSES & METHODS(CONT)
INPUT
▶ public class FileReader–convenience class for reading
character files
▶ public class BufferedReader–
❖ read text from a character input stream
❖ buffering characters so as to provide for the efficient reading
of characters, arrays and lines
❖ The buffer size may be specified or the default size may be
used
JAVA TEXT FILE CLASSES & METHODS(CONT)
INPUT(CONT)
▶ public class BufferedReader (cont.)
Example:
BufferedReader infile = new BufferedReader(new FileReader(“[Link]”));
//read buffered input from textfile
▶ This code will buffer the input from the specified file.
▶ Without buffering, each invocation of read() or readLine() could cause bytes
to be read from the file, converted into characters and returned –inefficient
JAVA TEXT FILE CLASSES & METHODS(CONT)
STEP READING TEXT FILE:
JAVA TEXT FILE CLASSES & METHODS(CONT)
Read text file
JAVA TEXT FILE CLASSES & METHODS(CONT)
Other Example Read text file
import [Link].*;
public class Numbers
{
public static void main(String [ ] args) throws IOException
{
FileReader fr = new FileReader(“[Link]”);
BufferedReader br = BufferedReader (fr);
String line = br. readLine();
while(line != null)
{
[Link](line);
line = [Link]( );
}
[Link] ( );
}
}