CSC2520
Data Structures and
Applications (06-07)
Tutorial 3
Basic I/O in Java
Basic I/O Concept
I/O stream
A sequence of data
Input stream
Read data from source to the program
Source – keyboard, files, network, etc
Output stream
Write data from the program to destination
Destination – screen, files, network, etc
Basic I/O Concept
Byte stream
Read or write data in bytes
Character stream
Read or write data in characters
E.g. FileReader, FileWriter
Buffered stream
More efficient
Read or write through memory area
E.g. BufferedReader, BufferedWriter
Scanner
Scanner
Belong to java.util package
Read from the input stream
Break down input into tokens
Use white space as separator
Translate tokens to different data types
Two important functions
next()
Return the next token (String)
hasNext()
Return if there is next token or not
Reading from command line
(keyboard)
Use system’s standard input stream
System.in
A byte stream
Put System.in as the input parameter for the
Scanner Obect
Scanner scan = new Scanner(System.in);
Reading from command line
(keyboard)
import java.util.*; Import the library java.util.*;
class T3Demo1
{
public static void main(String args[]) Create the Scanner to
{ read from the command line
boolean cont = true;
Scanner scan = new Scanner(System.in);
do
{
System.out.println("Please input a word (e to exit):");
String str = scan.next();
if (str.equals("e"))
{
cont = false; • Block until there is input
}
else
from the command line
{
System.out.println(str); • Return the input token
}
}
while (cont);
}
}
Reading from command line
(keyboard)
Sample output
Please input a word (e to exit):
abc
abc
Please input a word (e to exit):
123 456 789
123
Please input a word (e to exit):
456
3 tokens in a
Please input a word (e to exit):
line, so entering
789
the loop three
Please input a word (e to exit):
times
e
Reading from command line
(keyboard)
import java.util.*;
class T3Demo2
{
public static void main(String args[])
{
boolean cont = true;
Scanner scan = new Scanner(System.in);
do
{
System.out.println("Please input a word (-1 to exit):");
int i = scan.nextInt();
if (i == -1)
• Using nextInt() to read an integer
{
cont = false; • Other methods
} nextFloat(), nextLine()
else
{
System.out.println(i);
}
}
while (cont);
}
}
Reading from command line
(keyboard)
What happens if the input is not an integer in
the previous example?
How to solve it?
Output to screen
Use system’s standard output stream
System.out
System.out.println()
Print out the content and terminate the line
Support printing the string, int, boolean, etc…
System.out.print()
Print out the content
Support printing the string, int, boolean, etc…
Formatting
System.out.format(formatString, Object … arg
s)
Format multiple arguments based on the format
string
Similar to printf() in C
Example
System.out.format(“hello %s.%n”, str);
“hello %s.%n” is the format string
%s, %n are format specifiers
str is the argument
Formatting
class T3Demo6
{
public static void main(String args[])
{
int i = 123;
System.out.format("In decimal %d%n", i);
System.out.format("In octal %o%n", i);
System.out.format("In hexadecimal %x%n", i);
}
}
Output
In decimal 123
In octal 173
In hexadecimal 7b
File I/O
File class
Contain the file name
Create a file object by providing the pathname
Example
File f = new File(“File1”);
File f = new File(“C:\anyDir\File1”);
Provide a set of functions to examines and manipulate
s files
getName() – return the pathname
getAbsolutePath() – return the absolute pathname
pathcompareTo() – compare if the pathnames are the
same (true) or not (false)
E.g. file.compareTo(file1);
File I/O
FileReader Class
Character-input stream
Read characters from files
Example
FileReader fr = new FileReader(new File(“FileName”));
FileReader fr = new FileReader(“FileName”);
BufferedReader Class
Read text from a character-input stream
Buffering characters to improve the efficiency
Example
BufferedReader br = new BufferedReader(fr);
File I/O
Read from a file
1. Create the FileReader object
2. Create the BufferedReader object
3. Create the Scanner object
Scanner scan = new Scanner (br);
4. Read from the file through
next(), hasNext(), nextInt(), hasNextInt(), etc
5. Close the stream
close()
Step 5 is an important step to tell the system that yo
u have finished reading from the file
File I/O
import java.io.*; Import the package java.io.*;
import java.util.*;
class T3Demo3{
public static void main(String args[]){
if (args.length < 1){
System.out.println("Please input the file name.");
return;
}
Scanner scanner = null;
try{
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
scanner = new Scanner(br);
Try block
while (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}catch (IOException e){
e.printStackTrace(); Catch block
}finally{
if (scanner != null){
scanner.close(); Finally block
}
}
}
}
File I/O
Sample Output (reading from the class list)
The same as the input file
AU YEUNG WAN KIN
CHEUNG MING KAI
CHEUNG YU FAI
CHOW CHUN BONG
FUNG YU HIN
HO HON WAI
File I/O
IOException
A kind of exceptions
Is produced by failed I/O operations, such as File I/O
Must be handled (either by try-catch or throws)
Finally Block
Must be executed after the execution of try block (and
catch block)
close()
Is called in the finally block to ensure the input stream i
s closed
File I/O
FileWriter Class
Character-output stream
Write characters to files
Either overwrite (default) or append
Example
FileWriter fw = new FileWriter(“FileName”, true); //append
FileWriter fw = new FileWriter(“FileName”, false); //overwrite
FileWriter fw = new FileWriter(“FileName”); //overwrite
BufferedWriter Class
Write text to a character-output stream
Buffering characters to improve the efficiency
Example
BufferedWriter bw = new BufferedWriter(fw);
File I/O
PrintWriter Class
Print data to a text-output stream
Example
PrintWriter pr = new PrintWriter(bw);
Have methods similar to System.out
print(),println(), format(), etc…
File I/O
Write to a file
1. Create a FileWriter object
2. Create a BufferedWriter object
3. Create a PrintWriter object
4. Write to a file
5. Close the stream
File I/O
import java.io.*;
import java.util.*;
class T3Demo4{
public static void main(String args[]){
if (args.length < 1){
System.out.println("Please input the file name.");
return;
}
PrintWriter pw = null;
try{
FileWriter fw = new FileWriter(args[0]);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.println("hello");
}catch (IOException e){
e.printStackTrace();
}finally{
if (pw != null){
pw.close();
}
}
}
}
Self Exercise
1. Modify the T3Demo1, so the program takes
the whole line as a token
2. Modify the program in Q1, so the program
output the user input to a file
References
Basic I/O tutorial
http://java.sun.com/docs/books/tutorial/essential/io/index.html
Java 1.5.0 API
http://java.sun.com/j2se/1.5.0/docs/api/