You are on page 1of 13

9/11/2012

1
CSC238 OOP
Topic 08: FILES INPUT/OUTPUT
Introduction
The values of data structures in a program are lost when the
program terminates
If you want to keep the data after the program terminates, the data
need to be stored in a file or database need to be stored in a file or database
JAVA program can read a data and write a data from and to a file.
This process is called File Input/Output (I/O)
To store and retrieve data on a file in JAVA, it needs :
1. File
Any collection of data stored under a common name on a storage
medium other than memory is called data file, and it is referred to
t l fil as external file name.
2. File stream object
One-way transmission path that is used to connect a file stored on
a physical device such as disk to a program.
Each stream has its own mode whether the path will move the
data from a file into a program or from a program to a file
9/11/2012
2
A file stream that receives or reads data from a file into a program is referred to as
Input File Stream. Example input stream object is System.in object provides a
transmission path from keyboard to program.
A file stream that sends or writes a data to a file is referred to as Output File
Stream. Example output stream object is System.out object provides a
transmission path from program to monitor screen.
For each file that your program uses, a distinct file stream object must be created.
Files can be stored as character-based (text files) or byte-based (binary files) ( ) y ( y )
Basic I/O Stream Class Usage (to create input and output stream object)
These objects will open the I/O files to be read/written and referred to as
Input/Output file.
Mode Text File Binary File
Input FileReader class FileInputStream class
Output FileWriter class FileOutputStream class
Example :
Fi l eReader f r = new Fi l eReader ( pr i ce. t xt ) ;
//creates input stream object and cause the file price.txt to be opened for reading
f r . r ead( ) ; //once the object created, the file can be read from
Fi l Wi t Fi l Wi t ( t t t ) Fi l eWr i t er wr = new Fi l eWr i t er ( out . t xt ) ;
//creates outputstreamobject and cause the file out.txt to be created for writing
wr . wr i t e( ) ; //once the object created, the file can be written to
Closing a Stream Object
A file stream object is closed using classs cl ose( ) method. The
method closes the basic I/O stream object and all processing streams
created from it. created from it.
Example :
f r . cl ose( ) ; //close the object stream named fr - which is file price.txt
wr . cl ose( ) ; //close the object stream named wr which is file out.txt
9/11/2012
3
The File class
5
Every file is placed in a directory in the file system.
The complete file name consists of the directory path and the file name.
For example, c:\temp\Welcome.java is the complete file name for the file
Welcome.java on the windows operating system.
The File class contains the methods for obtaining file properties and for
renaming and deleting files. However, the File class does not contain the
methods for reading and writing file contents.
Th fil i t i Th Fil l i l f th fil The filename is a string. The File class is a wrapper class for the filename
and its directory path.
For example, new File(c:\\temp) creates a File object for the directory
c:\temp, and new File(c:\\temp\\test.txt) creates a File object for the file
c:\\temp\\test.txt, both on Windows.
Example: File class
6
import java.io.*;
import java.util.*;
public class TestFileClass {
public static void main(String[] args){
//create a File object
Fil fil Fil (" \\ \\di ") File file = new File("c:\\temp\\dict.txt");
System.out.println("Does it exist? " + file.exists());
//return true if the file or the directory represented by the File object exists
System.out.println("Can it be read? " + file.canRead());
//return true if the file represented by the File object exists and can be read
System.out.println("Can it be written? " + file.canWrite());
//return true if the file represented by the File object exists and can be written
System.out.println("Is it a directory? " + file.isDirectory()); //return true if the File object represents a directory
System.out.println("Is it a file? " + file.isFile());//return true if the File object represents a file
System.out.println("Is it absolute? " + file.isAbsolute());// return true if File object is created using an absolute path name
System.out.println("Is it hidden? " + file.isHidden());//return true if the file represented in the File object is hidden
System.out.println("What is its absolute path? " + file.getAbsolutePath());
//return the complete absolute file or directory name represented by the File object
System.out.println("What is its name? " + file.getName());
//return the last name of the complete directory and file name represented by the File object
System.out.println("What is its path? " + file.getPath());
//return the complete directory and file name represented by the File object
System.out.println("When was it last modified? " + new Date(file.lastModified()));
//return the time that the file was last modified
}
}
9/11/2012
4
Procedure of File I/O
Open a I/O stream objects (using Fi l eReader
or Fi l eWr i t er class)
Read/write a data to a I/O stream objects (using Read/write a data to a I/O stream objects (using
r ead( ) or wr i t e( ) methods)
Close the I/O stream objects (using cl ose( )
method)
Note: Note:
these 3 statements are of typed checked exceptions from
IOException class. So you need to handle or declare the
IOException exception.
Buffering
When transferring data between program and a file
using a buffered stream, it provides a storage area that
are used by the data as they are transferred to
enhance I/O speed and performance.
Buffered object stream are created from buffered stream
classes. The basic I/O stream object must be created first
before you create a buffered object stream.
Example :
Fi l eReader f r = new Fi l eReader ( pr i ce. t xt ) ;
Buf f er edReader br = new Buf f er edReader ( f r ) ;
Fi l eWr i t er wr = new Fi l eWr i t er ( out . t xt ) ;
Buf f er edWr i t er br = new Buf f er edWr i t er ( f r ) ;
9/11/2012
5
Reading and Writing Character-Based Files
Character-Based Output Stream Classes
Class Type Comments Common Methods
FileWriter Basic output Basic stream used for
h t b d t t
write(), flush(), close()
Character-Based Input Stream Classes
character-based output
BufferedWriter Buffering Provides output buffering,
which typically improves
performance
write(), flush(), close()
PrintWriter Processing Provides a number of
useful output methods
flush(), close(),
print(..), println(.)
Class Type Comments Common Methods
FileReader Basic Input Basic stream used for
character-based input
read()
BufferedReader Processing Provides buffering,
which typically improves
performance
read(), readLine(), close()
Example of Writing Character-based file
import javax.swing.*;
import java.io.*;
class WriteTextFile {
public static void main(String[] args) {
try
{
String input = JOptionPane.showInputDialog("Enter the file name:");
String fileName = input.trim();
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw );
PrintWriter pw = new PrintWriter(bw );
for(int i=1; i <= 10; i++)
pw.println("num: "+i);
Set up file and applying
3 classes FileWriter,
BufferedWriter and
PrintWriter
PrintWriterUse method println to write the statement
into output file by using object reference pw
//The given file name will be created in the current directory
pw.close();
}
catch (FileNotFoundException e)
{ System.out.println("Problem :"+e.getMessage()); }
catch (IOException ioe)
{ System.out.println("Problem :"+ioe.getMessage()); }
}
}
9/11/2012
6
Example of Reading Character-based file
import java.io.*;
class ReadTextFile {
public static void main ( String[] args ) {
String fileName = "thetest.txt";
int test;
try {
Input file: thetest.txt
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String input = null;
while( (input=br.readLine()) != null) {
test = Integer.parseInt(input);
System.out.println("Result is : "+(test));
}
br.close();
}
h (Fil N F dE i )
output
catch (FileNotFoundException e)
{ System.out.println("Problem :"+e.getMessage()); }
catch (IOException ioe)
{ System.out.println("Problem :"+ioe.getMessage()); }
}
}
Reading Character-Based file using String
Tokenizer
String Tokenizer
A class that helps programmer separates individual part of a string
if the items are separated by one character, such as a comma.
It helps the programmer when the program reads textual data from
a file.
For example: Data file contains a list of grocerys list.
A stringtokenizer object can help programmer to pullout
apples,milk,butter,cake
flour,sugar,cereal
apples,butter and place them in separate variables.
The java.util.StringTokenizer class is used to break strings into tokens
(words, numbers, operators, or whatever).
Tokens: the data of interest in a string of characters. They maybe
separated by a comma, a space, or one other special character.
9/11/2012
7
Reading Character-Based file using String
Tokenizer
A StringTokenizer constructor takes a string to break into tokens and
returns a StringTokenizer object for that string. Each time its
nextToken() method is called, it returns the next token in that string. If
you don't specify the delimiters (separator characters) blanks are the you don t specify the delimiters (separator characters), blanks are the
default.
Common methods used in String Tokenizer :
Assume that st is a StringTokenizer.
st.hasMoreTokens() -- Returns true if there are more tokens.
st.nextToken() -- Returns the next token as a String.
st.countTokens() -- Returns the int number of tokens.
Example : using String Tokenizer
import java.io.*;
import java.util.*;
class ReadTextFile2 {
public static void main ( String[] args ) {
String fileName = "grocery.txt";
int num;
try {
FileReader fr = new FileReader(fileName);
B fferedReader br ne B fferedReader(fr)
Input file: grocery.txt
BufferedReader br = new BufferedReader(fr);
String input = null;
int cnt=0;
while( (input=br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(input, ",");
cnt++;
System.out.println(cnt + " record");
while (st.hasMoreTokens()) {
String w = st.nextToken();
System.out.println(w);
}
}
br.close();
}
catch (FileNotFoundException e)
{ System.out.println("Problem :"+e.getMessage()); }
catch (IOException ioe)
{ System.out.println("Problem :"+ioe.getMessage()); }
}
}
9/11/2012
8
Scanner Class Scanner Class
Using Scanner for Input from file
The Scanner class is a class in j ava. ut i l , which allows the user to read
values of various types.
The Scanner looks for tokens in the input.
A k f h h d h h ll h A token is a series of characters that ends with what Java calls whitespace.
A whitespace character can be a blank, a tab character, a carriage return,
or the end of the file.
Thus, if we read a line that has a series of numbers separated by blanks,
the scanner will take each number as a separate token.
Whitespace characters (blanks or carriage returns) act as separators. The next
method returns the next input value as a string, regardless of what is keyed.
9/11/2012
9
Using Scanner for Input from file
Reading from the keyboard using Scanner
Scanner i n = new Scanner ( Syst em. i n) ;
To read from a file rather than the keyboard you instantiate a Scanner object To read from a file rather than the keyboard, you instantiate a Scanner object
with a Fi l eReader object rather than Syst em. i n.
Scanner i nFi l e = new Scanner ( new Fi l eReader ( ( "i nFi l e. dat ") ) ;
Although all of the methods applied to keyboard input can be applied to file input,
there are methods that are usually applied only to files.
These are the methods that ask of there are more values in the file. If there are no
more values in a file, we say that the file is at the end of the file (EOF). For
example :
i nFi l e. hasNext ( ) ; //returns true if inFile has another token in the file
i nFi l e. hasNext Li ne( ) ; //returns true if inFile has another line the file
Be sure to close all files. If you forget to close Syst em. i n, no harm is done, but
forgetting to close a file can cause problems.
Example : Using Scanner for Input from file
import java.io.*;
import java.util.*;
class readScanner {
public static void main ( String[] args ) {
//String fileName = "inFile.dat";
Input file: inFile.dat
int test;
try {
Scanner inFile = new Scanner(new FileReader("inFile.dat"));
while(inFile.hasNextLine()) {
String name = inFile.next();
int mark = inFile.nextInt();
System.out.println(name+" "+mark);
}
inFile.close();
output
();
}
catch (FileNotFoundException e)
{ System.out.println("Problem :"+e.getMessage()); }
catch (IOException ioe)
{ System.out.println("Problem :"+ioe.getMessage()); }
}
}
9/11/2012
10
Exception handling Exception handling
Introduction
Exception handling is used to deal with runtime errors
Exception may occur for various reasons such as:
Entering an invalid input Entering an invalid input
The program may attempt to open a file that doesnt
exist
Network connection may hang up
The program may attempt to access an out of bounds
array element array element
A Java exception is an instance of a class derived
from Throwable class which contained in the
java.lang package and subclasses of Throwable are
contained in various packages
9/11/2012
11
Some of Javas Exception Classes
Handling exception
3 statements
try
Identifies a block of statements within which an exception Identifies a block of statements within which an exception
might be thrown
catch
Must be associated with a try statement and identifies a
block of statements that can handle a particular type of
exception occurs within the try block
finally finally
Used to execute some code if an exception occurs or is
caught
Must be associated with a try statement and identifies a
block of statements that are executed regardless whether
or not an error occurs within the try block
9/11/2012
12
Example
Binary I/O classes
InputStream is the root for binary input classes and
OutputStream is the root for binary output classes
9/11/2012
13
FileInputStream/FileOutputStream
For reading/writing bytes from/to a file
Exercise
Application of StringTokenizer class to divide one statement
into several words
Write a program to read from a file name score.txt which
contains several numbers shown as follows:
Write the output to calculate the total score for each student to
a text file name scoreout.txt shown as follows:

You might also like