0% found this document useful (0 votes)
6 views

CMP202 Lecture 5 - Text File IO

Uploaded by

Akorede Bashir
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CMP202 Lecture 5 - Text File IO

Uploaded by

Akorede Bashir
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

CMP 202- COMPUTER PROGRAMMING

II
LECTURE SERIES
OVERVIEW OF THE COURSE OUTLINE
Principles of Good programming
Structured programming concepts
Errors and Debugging
Testing
Text Files and IO
Text File I/O
• The java.io package contains nearly every class needed to perform input and
output (I/O) in Java. All these streams represent an input source and an output
destination.
• The stream in the java.io package supports many data such as primitives,
object, localized characters, etc.
• Stream
• A stream can be defined as a sequence of data. There are two kinds of
Streams:
• InPutStream: The InputStream is used to read data from a source. This stream is used
for reading data from the files.
• Objects can be created using the keyword new and there are several types of constructors available.
• OutPutStream: The OutputStream is used for writing data to a destination. This stream
is used to create a file and write data into it.
• The stream would create a file, if it doesn't already exist, before opening it for output.
Stream

• Java provides strong but flexible support for I/O related to files.
• The Files can be classified into two major categories: Binary files and Text
files.
• A binary file is a file whose contents must be handled as a sequence of binary digits.
• A text file is a file whose contents are to be handled as a sequence of characters.
• Why use files for I/O?
• Files provide permanent storage of data.
What are Standard Streams?
• All the programming languages provide support for standard I/O where
the user's program can take input from a keyboard and then produce an
output on the computer screen.
• Recall that, in Java the I/O is handled by objects called streams. Java
provides the following three standard streams as described as follows:
• Standard Input: This is used to feed the data to user's program and usually
a keyboard is used as standard input stream and represented as System.in.
• Standard Output: This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream
and represented as System.out.
• Standard Error: This is used to output the error data produced by the
user's program and usually a computer screen is used for standard error
stream and represented as System.err.
Java BufferedReader Class
• Java BufferedReader class is used to read the text from a character-
based input stream.
• It can be used to read data line by line by readLine() method.
• It makes the performance fast. It inherits Reader class.
• Let's see the declaration for Java.io.BufferedReader class:
public class BufferedReader extends Reader
Java BufferedReader class constructors
• The following table summarizes the constructors and their description
Java BufferedReader class methods
Opening a text file for reading
• A stream of the class BufferedReader is created and connected to a text file for
reading as follows:
BufferedReader streamName = new BufferedReader(new FileReader(filename));

• Where, filename is a File object or a constant string or a String variable


containing the name or the full path of the file to be read.
• Example of valid filenames:
“myinput.txt”,“C:\\homework\\StudentTest.java”, “C:/homework/StudentTest.java”

• Both BufferedReader and FileReader classes belong to the java.io


package. The FileReader constructor throws a
FileNotFoundException, if the text file to be opened for reading does
not exist.
• The FileNotFoundException is a subclass of the class IOException.
Closing a stream
• When a program has finished writing to or reading from a file, it
should close the stream connected to that file by calling the close
method of the stream:
streamName.close();

• The close method is defined as:


public void close() throws IOException
• When a stream is closed, the system releases any resources used to
connect the stream to a file.
• If a program does not close a stream before the program terminates,
then the system will automatically close that stream.
Reading a text file
After a stream has been connected to a text-file for reading, the readLine or read
methods of the stream can be used to read from the file:
• public String readLine()throws IOException
• public int read()throws IOException
• The readLine method reads a line of input from the file and returns that line as
a string. If readLine attempts is to read beyond the end of file, null is returned.
• The read method reads a single character from the file and returns that
character as an integer value.
• To obtain the character, a type cast is required:
char next=(char) inputStream.read();
• If read attempts is to read beyond the end of the file, -1 is returned.
• Note: A Type Casting is when a value of one primitive data type is assign to
another type such as int to double or double to int.
Reading a Text File: Example1
• The following program displays the contents of the file myinput.txt on
the screen by reading one character at a time:
Reading a text file: Example2
• The following program displays the ID, number of quizzes taken, and
average of each student in grades.txt:
Reading a text file: Example2 –Additional Explanation

• Note: A StringTokenizer class breaks a string into tokens. It uses the


following methods as shown in the program above:
• nextToken() - Returns the next token from the StringTokenizer object.

• countTokens() – Returns the total number of tokens.

• hasMoreTokens() – Checks if there are more tokens


Opening a text file for Writing
• A stream is created and connected to a text file for writing by a statement of the form:
PrintWriter streamName =new PrintWriter(new FileWriter(filename));
• Any preexisting file by the same name and in the same folder is destroyed. If the file
does not exist it is created.
• A stream is created and connected to a text file for appending by a statement of the
form:
PrintWriter streamName = new PrintWriter(new FileWriter(filename , true));
• Any preexisting file by the same name is not destroyed. If the file does not exist it is
created.
• Both PrintWriter and FileWriter classes belong to java.io package. FileReader uses
FileInputStream and FileWriter uses FileOutputStream.
• But note that, the FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.
Writing to a Text File
• The PrintWriter class has methods print and println.
• The print method prints output without generating a new line.
• The println method prints output, it then generates a new line.
• Each constructor of the FileWriter can throw an IOException:
public FileWriter(String filename) throws IOException
public FileWriter(String filename , boolean appendFlag)throws IOException
Example: Appending to a Text-file
The following program appends a message to the file datafile.txt
Example: Writing to a Text-file
The following program copies the first 200 non-blank characters from one file to another.

You might also like