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

Chapter 5

This document discusses file input/output in Java, including: 1. Reading and writing text files using classes like FileReader, BufferedReader, FileWriter, and PrintWriter. 2. The steps to open, read/write, and close both input and output text files. 3. Sample programs that demonstrate reading a text file, writing to multiple text files, and reading from one file and writing to another.

Uploaded by

Sarah Naddhirah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Chapter 5

This document discusses file input/output in Java, including: 1. Reading and writing text files using classes like FileReader, BufferedReader, FileWriter, and PrintWriter. 2. The steps to open, read/write, and close both input and output text files. 3. Sample programs that demonstrate reading a text file, writing to multiple text files, and reading from one file and writing to another.

Uploaded by

Sarah Naddhirah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

CSC238/435 – OOP

TOPIC 8 : FILE INPUT- OUTPUT

Types Of File Input/Output

Java can read several types of information from files: binary, Java objects, text, zipped
files, etc. The most common types of files are:

 Text files - A sequence of characters

 Binary files - A sequence of bits

I/O classes are listed in java.io package.

Text Files

 Reading Text Files

Classes from java.io package:

Classes Descriptions

FileReader Convenience class for reading character


files.
Throws: FileNotFoundException

BufferedReader Read text from a character-input stream,


Methods Descriptions buffering characters so as to provide for the
efficient reading of characters, arrays, and
read() Read a single lines.
character; eof is –1
readLine() Read a string line; Throws: IOException
return a string
close() Close the input stream
Steps:

1. To open a file, make a File or FileReader input object and link it with an
external existing file name:

FileReader reader = new FileReader (“data.txt”);

2. Create a Java input stream object and attached it to a file

BufferedReader infile = new BufferedReadear (reader);

3. Read the contents of the file and process the data

4. Close the file

infile.close();

Zulaile Mabni 2010 1


Sample Program (Reading a text file):

import java.io.*;

public class FileInput


{
public static void main(String []arg) throws IOException
{
try
{
FileReader reader = new FileReader("data.txt");
BufferedReader in = new BufferedReader(reader);

String name = null; float score, total = 0;

while ((name = in.readLine())!=null)


{
score = Float.parseFloat(in.readLine());
total += score;
System.out.println("Name:"+ name + "Score:" + score);
}
System.out.println("Total score : " + total);

in.close();
} // end try

catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch(EOFException eof) {
System.out.println(eof.getMessage());
}
catch(IOException io) {
System.out.println(io.getMessage());
}
} // end main
} // end class

Sample Input File

Zulaile Mabni 2010 2


Classes from java.util package:

For Java 5.0, the Scanner class can be used for text input, which is more convenient.

It is a simple text scanner which can parse primitive types and strings using regular
expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default
matches whitespace. The resulting tokens may then be converted into values of different
types using the various next methods.

Classes Descriptions

Scanner A simple text scanner which can


Methods Descriptions parse primitive types and strings
using regular expressions.
hasNext() Returns true if this
scanner has another Throws: IOException
token in its input
hasNext<Wrapper>() Returns true if this
i.e. scanner has another
hasNextInt() token of
type<Wrapper> in its
input
next() Finds and returns the
next complete token
next<Wrapper>() Finds and returns the
i.e. next complete token
nextInt() of type<Wrapper>
close() Close the scanner

Sample Program:

Scanner in = new Scanner("myData.txt");


while (in.hasNextLine())
{
String line = in.nextLine();
// process line
}

in.close();

Zulaile Mabni 2010 3


//@author Zulaile Mabni

import java.io.*;
import java.util.*;

public class FileInput


{
public static void main(String []arg) throws IOException
{
try
{
File reader = new File("C:/", "data.txt");
Scanner in = new Scanner(reader);

String name = null; float score, total = 0;

while (in.hasNextLine())
{
name = in.next();
score = in.nextFloat();
total += score;
System.out.println(" Name: " + name + "Score: " +
score);
}

System.out.println("Total score : " + total);

in.close();

} // end try

catch(IOException io) {
System.out.println(io.getMessage());
}

}
}

Zulaile Mabni 2010 4


 Writing Text Files

Classes from java.io package:

Classes Descriptions

FileWriter Convenience class for writing character files.


Throws: IOException

PrintWriter Print formatted representations of objects to


Methods Descriptions a text-output stream.
print(x) print x; x is a char,
int,etc. String or Throws: FileNotFoundException
Object
println(x) print x & terminate
the line; x is a
char, int,etc.
String or Object
close() Close the output stream

Steps:

1. Make a File or FileWriter output object to link it with an external file name:

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

2. Create a Java output stream object and attached it to a file

PrintWriter outfile = new PrintWriter (writer);

3. Write the contents of the file

4. Close the file

outfile.close();

Zulaile Mabni 2010 5


Sample program(Writing Text Files):

import java.io.*;
import javax.swing.*;

public class FileOutput


{
public static void main(String []arg) throws IOException
{
try
{
FileWriter file1 = new FileWriter("odd.txt");
FileWriter file2 = new FileWriter("even.txt");
PrintWriter out1 = new PrintWriter(file1);
PrintWriter out2 = new PrintWriter(file2);

for (int k=0; k< 5; k++)


{
String num = JOptionPane.showInputDialog("Enter a
number ");
int number = Integer.parseInt(num);
if (number%2==0)
out2.println(number);
else
out1.println(number);

} // end for

// close the files to make sure that all output are written to the files
out1.close();
out2.close();

}//end try

catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}

catch(EOFException eof) {
System.out.println(eof.getMessage());
}

catch(IOException io) {
System.out.println(io.getMessage());
}

catch(Exception nf) {
System.out.println(nf.getMessage());
}
} // end main
} // end class

Zulaile Mabni 2010 6


Sample Program (Reading and Writing Text Files):

//@author Zulaile Mabni


import java.io.*;
import javax.swing.*;

public class FileInputOutput


{
public static void main(String []arg) throws IOException
{
String inFile = JOptionPane.showInputDialog(" Enter input
filename:");
String outFile = JOptionPane.showInputDialog(" Enter output
filename:");
try
{
FileReader reader = new FileReader(inFile);
BufferedReader in = new BufferedReader(reader);

FileWriter writer = new FileWriter(outFile);


PrintWriter out = new PrintWriter( writer);

String name = null; float score, total = 0;

while ((name = in.readLine()) != null)


{
score = Float.parseFloat(in.readLine());
total += score;
out.println(" Name: " + name + "Score: " +
score);
}

out.println("Total score : " + total);

in.close();
out.close();

} // end try
catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch(EOFException eof) {
System.out.println(eof.getMessage());
}
catch(IOException io) {
System.out.println(io.getMessage());
}
}// end main
}// end classFileInputOutput

Zulaile Mabni 2010 7


//@author Zulaile Mabni

import java.io.*;
import javax.swing.*;
import java.util.*;

public class FileInputOutput2


{
public static void main(String []arg) throws IOException
{
String inFile = JOptionPane.showInputDialog(" Enter input
filename:");
String outFile = JOptionPane.showInputDialog(" Enter output
filename:");

try
{
FileReader reader = new FileReader(inFile);
BufferedReader in = new BufferedReader(reader);

FileWriter writer = new FileWriter(outFile);


PrintWriter out = new PrintWriter( writer);

String inData = null; float total = 0;

while ((inData = in.readLine()) != null)


{
StringTokenizer st = new StringTokenizer(inData,",");
String name = st.nextToken();
String sc = st.nextToken();
float score = Float.parseFloat(sc);
String grade = st.nextToken();

total += score;
out.println("Name: " + name + " Score: " + score + "
Grade:" + grade);
}

out.println("Total score : " + total);


in.close();
out.close();

} // end try

catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}

catch(EOFException eof) {
System.out.println(eof.getMessage());
}

catch(IOException io) {
System.out.println(io.getMessage());
}
}
}

Zulaile Mabni 2010 8


Sample Input File:

Sample Output File:

Zulaile Mabni 2010 9


REFERENCES

Deitel, Java How To Program, 5th Edition, Prentice Hall, 2003

Horstmann, Java Concepts, 4th Edition, John Wiley, 2005

Savitch W. Absolute Java. 2nd Edition. Addison Wesley 2006.

Wu, An Introduction To Object-Oriented Programming With Java, 4th Edition, McGraw-


Hill, 2006

http://java.sun.com

Zulaile Mabni 2010 10

You might also like