Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

CHAPTER 7

File Input/Output

By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Science, UiTM
Perlis
Objectives
• By the end of this chapter, students should be able to:

Be able to read and write text files.

Become familiar with the concepts of text


files format.

Write an application program to implement


text files format.
2
Introduction
(Why use File?)
• The keyboard input and screen output deal with
temporary data.
When the programs ends, the data typed at
keyboard and left on the screen go away.

• Files provides a way to store data permanently.

Data in the file remains after program


execution ends.
3
Introduction
(Why use File?)
• An input file can be used over and over
again by different programs, without the
need to type the data again for each
program.

• File provides with a convenient way to


deal with large quantities of data.
4
Introduction
(Advantages)

Advantages

Save data in Do not have


a secondary to waste
storage. typing.
5
Introduction
(Terms)

Character
the smallest
Field
data, any one
of letters, grouped of
Record
numbers, related
character; field are
File
special
symbols on the meaningful grouped
together. related records
Database
keyboard or data such as
hidden name, age. are grouped
together. consists of
computer several related
characters. files.

6
Introduction
(The Concept of a Stream)
• In java, file I/O, as well as simple keyboard and screen I/O, is
handled by stream.

• A stream is a flow of data. The data might be characters,


numbers, or bytes consisting of binary digits.

• If data flows into your program, the stream called an Input


stream.

• If data flows out of your program, the stream is called an


output stream.
7
Introduction
(The Concept of a Stream)

Input and Output Stream


• Stream is implemented as objects of special stream classes:
 Class Scanner -> have been using for keyboard input, are input
stream
 Object System.out -> output stream

We discuss streams that connect your program to files instead


of to the keyboard or display on screen.
8
Text Files and Binary Files

• There are two fundamentally different ways to


store data:

File

Text Binary
Text files
files file
9
Text Files
• All of the data in any file is stored as binary digits
(bits) – sequence of 0s and 1s.

• However, in some situations, we don’t think of file’s


contents as a sequence of binary digits. Instead, we
think of them as a sequence of characters.

• Files that are thought of as sequences of character,


and that have streams and methods to make the
binary digits look like characters to your program 10
and
your text editor, are called text files.
Text Files

• In text format, data items are represented


in human-readable form, as a sequence of
characters.

• For example, the integer 12,345 is stored


as the sequence of five characters:
‘1’ ‘2’ ‘3’ ‘4’ ‘5’
11
Streams, Reader and Writer
• If you store information in text form, as a sequence of
characters, you need to use the Reader and Writer class and
their subclasses to process input and output.

• Text input and output are more convenient for humans,


because it is easier to produce input (just use a text editor) and
it is easier to check that output is correct (just look at the output
file in an editor).

• However, binary storage is more compact and more efficient.

12
Reading and Writing Data
(Basic Operations for Writing to a File)
• Six basic operations:
Writing to a File
Create and save an empty data file using non-document
text editor. (Optional)
Create a class (an application class) as a medium of writing
data to the data file.
In the class, create a variable to represent the data file in
the program.
Then, create an output stream and attach it to the file
variable.

Write data to file by using the output stream.

Close the stream.


13
Reading and Writing Data
(Basic Operations for Reading From a
File)
• Six basic operations:
Reading From a File
There is existing a data file created. (Compulsory)

Create a class (an application class) as a medium of


reading data from the data file.
In the class, create a variable to represent the data file in
the program.
Then, create an input stream and attach it to the file
variable.

Read data from the file by using the input stream.

Close the stream.


14
Creating a Text File
(Exception handling)
• An exception – refers to an expected or error in
a program.

• Many errors such as:


You write data to a disk, but the disk is full or
unformatted.
Your program asks for user input, but the user
enters invalid data.
15
Creating a Text File
(Exception handling)
• Types of exceptions:

Exception

Checked Unchecked

• Checked at compiled time • Unchecked at compiled time and


• Thrown by a Java method. detected only at run time
• Example: FileNotFoundException • The runtime system or the Java
virtual Machine (JVM) throws
exceptions of these types. 16
• Example: ArrayIndexBoundsException.
Creating a Text File
(Exception handling)
• Exceptions Statement:
indicate that a block of code
could potentially cause
try exceptions to be thrown.

catch exception block


Will cater for some code
thrown by try for
that you want them to finally Exception catch handling the exception
be executed, whether
or not any exceptions
were thrown.

throw Used explicitly throw an


exception.
17
Text – File Input/Output
• To read text data from a disk file, you can create a
FileReader object.
FileReader reader = new FileReader (“input.txt”);

• Similarly, you can use FileWriter object to write data


to a disk file in text form:

FileWriter writer = new FileWriter(“Output.txt”);

18
Text – File Input/Output
• We can solve the problem by using three different
approaches:
Approaches
(File I/O)

main method OOP approach


Just involve
(using specific
main method + class + main
only Parallel Array method)

19
Reading and Writing - File
(Example)

Example of Input file:


input.txt

Example of output file: pass.txt and fail.txt


20
Reading and Writing - File
(Example 1 – Using main method only)
import java.io.*;
import java.util.StringTokenizer;

public class runnerApp


{ STEP 1: Exception
public static void main(String args[])
Handling (Block Try)
{
try{
BufferedReader in = new BufferedReader (new
STEP 2: FileReader("D:\\runner.txt"));
Open ALL PrintWriter outPass = new PrintWriter (new
file (Input + BufferedWriter(new FileWriter("D:\\pass.txt")));
Output) PrintWriter outFail = new PrintWriter (new
BufferedWriter(new FileWriter("D:\\fail.txt")));

21
Reading and Writing - File
(Example (Example 1 – Using main
method only)
STEP 3: Read data from
String inData = null;
while((inData = in.readLine()) != null) input
file (as record)
{
StringTokenizer st = new StringTokenizer (inData,";");
String name = st.nextToken();
STEP 4: Tokenize
double time1 = Double.parseDouble(st.nextToken()); the record into
double time2 = Double.parseDouble(st.nextToken(););
double time3 = Double.parseDouble(st.nextToken(););
field/attribute
double average = (time1 + time2 + time3)/3;

if(average <=11.00) STEP 5: Manipulation/


outPass.println(name +";"+average); Processes
else
outFail.println(name +";"+average);

}//end while

in.close();
outPass.close(); STEP 6: Close ALL files
outFail.close();
}//end try
STEP 7: End block try
22
Reading and Writing - File
(Example (Example 1 – Using main
method only))
catch(FileNotFoundException fe)
{
System.out.println(fe.getMessage());
}
STEP 8:
catch(IOException iox) Exception
{ Handling
System.out.println(iox.getMessage()); (Catch Block)
}

catch(Exception e)
{
System.out.println("problem: " +e.getMessage());
}
}//end main
}//end class

23
Reading and Writing - File
(Example 2 – Using an Array)
import java.io.*;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

public class runnerApp


{
public static void main(String args[])
{
String[] name = new String[100]; STEP 1: Declare all
double[] time1 = new double[100]; variables as array to
double[] time2 = new double[100]; hold each attribute
double[] time3 = new double[100]; from file.
int cnt = 0;

24
Reading and Writing - File
(Example 2 – Using an Array)
STEP 2: Exception
try{
BufferedReader in = new BufferedReader (new Handling (Block
Try)
STEP 3: FileReader("D:\\runner.txt"));
Open PrintWriter outPass = new PrintWriter (new BufferedWriter(new
ALL file FileWriter("D:\\pass.txt")));
PrintWriter outFail = new PrintWriter (new BufferedWriter(new
(Input +
FileWriter("D:\\fail.txt")));
Output) STEP 4: Read data from
String inData = null; input file (as record)
while((inData = in.readLine()) != null)
{
StringTokenizer st = new StringTokenizer (inData,";"); STEP 5:
name[cnt] = st.nextToken(); Tokenize
time1[cnt] = Double.parseDouble(st.nextToken()); the record
time2[cnt] = Double.parseDouble(st.nextToken());
time3[cnt] = Double.parseDouble(st.nextToken()); into field/
cnt++; attribute
}//end while
STEP 6: Count
records
25
Reading and Writing - File
(Example 2 – Using an Array)
for(int i=0; i<cnt; i++)
{
double average = (time1[i] + time2[i] + time3[i])/3;

STEP 7 : if(average <=11.00)


Manipulation outPass.println(name[i] +";"+average);
/ Processes else
outFail.println(name[i] +";"+average);

}//end for

in.close();
outPass.close(); STEP 8: Close ALL files
outFail.close();
}//end try
STEP 9: End block try

26
Reading and Writing - File
(Example 2 – Using an Array)
catch(FileNotFoundException fe)
{
System.out.println(fe.getMessage());
}
STEP 10:
catch(IOException iox) Exception
{ Handling
System.out.println(iox.getMessage()); (Catch Block)
}

catch(Exception e)
{
System.out.println("problem: " +e.getMessage());
}
}//end main
}//end class

27
Reading and Writing - File
(Example 3 – Using OOP)
import java.util.*;
import java.io.*;

public class Runner{


private String name;
private double time1;
private double time2;
private double time3;

//Default constructor
public Runner()
{
name = "";
time1 = 0;
time2 = 0;
time3 = 0;
}

28
Reading and Writing - File
(Example 3 – Using OOP)
//Normal constructor
public Runner(String nm, double tm1, double tm2, double tm3)
{
name = nm;
time1 = tm1;
time2 = tm2;
time3 = tm3;
}

//Setter
public void setName(String nm)
{
name = nm;
}

public void setTime1(double tm1)


{
time1 = tm1;
} 29
Reading and Writing - File
(Example 3 – Using OOP)
public void setTime2(double tm2)
{
time2 = tm2;
}

public void setTime3(double tm3)


{
time3 = tm3;
}
//Getter
public String getName()
{
return name;
}

public double getTime1()


{
return time1;
} 30
Reading and Writing - File
(Example 3 – Using OOP)
public double getTime2()
{
return time2;
}

public double getTime3()


{
return time3;
}

//Processor
public double calAverage()
{
return ((time1+time2+time3)/3.0);
}

31
Reading and Writing - File
(Example 3 – Using OOP)
//Printer
public String toString()
{
return "\nName: "+name + "\nTime 1:"+Time1+"\nTime 2:“
+time2+"\nTime 3: "+time3;
}

32
Reading and Writing - File
(Example 3 – Using OOP)
import java.util.*;
import java.io.*;

public class RunnerApp


{
public static void main(String[] args) STEP 1: Exception
{ Handling (Block Try)
int cnt = 0;

try{
BufferedReader in = new BufferedReader (new
FileReader("E:\\runner.txt"));
STEP 2: PrintWriter outPass = new PrintWriter (new
Open ALL BufferedWriter(new FileWriter("E:\\pass.txt")));
file (Input + PrintWriter outFail = new PrintWriter (new
Output) BufferedWriter(new FileWriter("E:\\fail.txt")));

33
Reading and Writing - File
(Example 3 – Using OOP)
STEP 3: Declare array
//Declare an array of object of object
Runner[] run = new Runner[100];

String inData = null; STEP 4: Read data from


while((inData = in.readLine()) != null) input file
{
StringTokenizer st = new StringTokenizer (inData,";");
STEP 5: String name = st.nextToken();
Tokenize double tm1 = Double.parseDouble(st.nextToken());
double tm2 = Double.parseDouble(st.nextToken());
the record
double tm3 = Double.parseDouble(st.nextToken());
into field/
attribute //Instantiate and store onto array of object
run[cnt]= new Runner(name,tm1,tm2,tm3);
cnt++;
}//end while STEP 6: Store attributes
STEP 7: Count onto array of object
records
34
Reading and Writing - File
(Example 3 – Using OOP)
//To filter into 2 different files based on the average time.
for (int i = 0; i<cnt; i++) STEP 8: Manipulation/
{ Processes
if(run[i].calAverage() <=11.00)
outPass.println(run[i].getName() +";"+run[i].calAverage());
else
outFail.println(run[i].getName() +";"+run[i].calAverage());
}//end for

in.close();
outPass.close(); STEP 9: Close ALL files
outFail.close();
}//end try
STEP 10: End block try

35
Reading and Writing - File
(Example 3 – Using OOP)
catch(FileNotFoundException fe)
{
System.out.println(fe.getMessage());
}
STEP 11:
catch(IOException iox) Exception
{ Handling
System.out.println(iox.getMessage()); (Catch Block)
}

catch(Exception e)
{
System.out.println("problem: " +e.getMessage());
}
}//end main
} //end class

36
The End
Q&A
37

You might also like