Files
Files
Chapter
File Input/Output
File Input/Output
Dr. S. HAMMAMI
Chapter 3: Objectives
• After you have read and studied this chapter, you should
be able to
– Include a JFileChooser object in your program to let the user
specify a file.
– Write bytes to a file and read them back from the file, using
FileOutputStream and FileInputStream.
– Write values of primitive data types to a file and read them back
from the file, using DataOutputStream and DataInputStream.
– Write text data to a file and read them back from the file, using
PrintWriter and BufferedReader
– Write objects to a file and read them back from the file, using
ObjectOutputStream and ObjectInputStream
Files
There are two general types of files you need to learn about: text files
and binary files…
– End-of-file marker
– Count of total bytes in file
– Java program processing a stream of bytes receives an
indication from the operating system when program reaches
end of stream
• Binary files – created from byte-based streams, read by a program that converts
data to human-readable format
• Text files – created from character-based streams, can be read by text editors
– System.in – standard input stream object, can be redirected with method setIn
– System.out – standard output stream object, can be redirected with method setOut
– System.err – standard error stream object, can be redirected with method setErr
The Class File
Opens
Opensthethefile
filesample.dat
sample.dat
File filename = new File(“sample.dat”); ininthe current directory.
the current directory.
Opens
O p e n sthe
th e file
file test.dat
te st.d a tin
in the
th e directory
d ire c to ryC:\SamplePrograms
C :\S a m p le P ro g ra m susing
u s in g the
th e
generic file separator / and providing the full pathname.
g e n e ric file s e p a ra to r / a n d p ro v id in g th e fu ll p a th n a m e .
2. Takes two Strings, first specifying path and second specifying name of file
To seeififfilename
Tosee filenameisis
if (filename.exists( ) ) { associated
associatedtotoaareal
realfile
file
correctly.
correctly.
ToToseeseeififfilename
filenameisis
if (filename.isFile() ) { associated
associatedtotoaafilefileor
ornot.
not.
IfIffalse, it is a directory.
false, it is a directory.
1
2 // Testing the FileDemonstration class.
3 import java.util.Scanner;
4
5 public class FileDemonstrationTest
6 {
7 public static void main( String args[] )
8 {
9 Scanner input = new Scanner( System.in );
10 FileDemonstration application = new FileDemonstration();
11
12 System.out.print( "Enter file or directory name here: " );
13 application.analyzePath( input.nextLine() );
14 } // end main
15 } // end class FileDemonstrationTest
Enter file or directory name here: C:\Program Files\Java\jdk1.5.0\demo\jfc
jfc exists
is not a file
is a directory
is absolute path
Last modified: 1083938776645
Length: 0
Path: C:\Program Files\Java\jdk1.5.0\demo\jfc
Absolute path: C:\Program Files\Java\jdk1.5.0\demo\jfc
Parent: C:\Program Files\Java\jdk1.5.0\demo
Directory contents:
CodePointIM
FileChooserDemo
Font2DTest
Java2D
Metalworks
Notepad
SampleTree
Stylepad
SwingApplet
SwingSet2
TableExample
FileOutputStream
Data
FileInputStream
Data
Opening a Binary File for Output
Using the FileOutputStream class, create a file stream and connect it to a
physical disk file to open the file. We can output only a sequence of bytes.
Import java.io.*
Class TestFileOuputStream {
Public static void main (String [] args) throws IOException
{
//set up file and stream
File F = new File("sample1.data");
//data to save
byte[] A = {10, 20, 30, 40,50, 60, 70, 80};
ToToensure
ensurethat
thatallalldata
dataare
aresaved
savedtotoaa
//output done, so close the stream file,close
closethe
thefile
fileatatthe
theend
endofofthe
thefile
file
OutF.close(); file,
access.
access.
}
}
Opening a Binary File for Input
Using the FileInputStream class, create a file stream and connect it to a
physical disk file to open the file.
Import java.io.*
Class TestFileInputStream {
Public static void main (String [] args) throws IOException
{
//set up file and stream
File G = new File("sample1.data");
FileInputStream InG = new FileInputStream(G);
The order of write and read operations must match in order to read the stored
primitive data back correctly.
Textfile Input and Output
– This allows us to view the file content using any text editor
– From Java 5.0 (SDK 1.5), we can also use the Scanner class for
inputting textfiles
Text File Stream Classes
import java.io.*;
class TestPrintWriter {
public static void main (String[] args) throws IOException {
To read the data from a text file, we use the FileReader and
BufferedReadder objects.
String str;
str = bufReader.readLine();
outObjecttStream.writeObject(p);
}
outObjectStream.close();
}
}
Saving Objects
It is possible to save different type of objects to a single file. Assuming the Account and
Bank classes are defined properly, we can save both types of objects to a single file:
File
FileoutFile
outFile==new
newFile("objects.data");
File("objects.data");
FileOutputStream
FileOutputStream outFileStream
outFileStream==new
newFileOutputStream(outFile);
FileOutputStream(outFile);
ObjectOutputStream
ObjectOutputStreamoutObjectStream
outObjectStream==new
newObjectOutputStream(outFileStream);
ObjectOutputStream(outFileStream);
outObjectStream.writeInt( 15 );
outObjectStream.writeObject( account1 );
outObjectStream.writeChar( ‘X’ );
Reading Objects
To read objects from a file, we use FileInputStream and ObjectInputStream.
We use the method readObject to read an object.
import java.io.*;
Class TestObjectInputStream {
public static void main (String[] args) throws IOException {
File inFile = new File("objects.data");
FileInputStream inFileStream = new FileInputStream(inFile);
ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
Person p;
for (int i =0; i<10; i++) {
p = (Person) inObjectStream.readObject();
System.out.println(p.getName() + “ “ + p.getAge() + “ “ +p.getGender());
}
inObjectStream.close();
}
}
Reading Objects
If a file contains objects from different classes, we must read them in the
correct order and apply the matching typecasting. For example, if the file
contains two Account and two Bank objects, then we must read them in the
correct order:
Course
- name: String
- creditHours: int
Department
+ Course(String, int)
+ display()
- name: String + setName(String)
+ setCreditHs(int)
+ Department(int size) + getCreditHours()
+ setDepartment()
+ averageCredit():double
+ display()
+ openOutputFile(String)
+ openInputFile(String)
Example: Class Department
Implementation of Class Course
importjava.io.*;
java.io.*; publicvoid
public voidsetName(String
setName(Stringna)
na)
import
publicclass
public classCourse
Courseimplements
implementsSerializable
Serializable {{
name=na;
{{ name=na;
privateString
private Stringname;
name; }}
privateint
intcreditHours;
creditHours; publicvoid
public voidsetCreditHs(int
setCreditHs(inth)h)
private
publicCourse
public Course(String
(Stringna,
na,int
inth)h) {{
creditHours=h;
{{ creditHours=h;
name=na;
name=na; }}
creditHours=h; publicdouble
public doublegetCreditHours()
getCreditHours()
creditHours=h;
}} {{
publicvoid
voiddisplay()
display() returncreditHours;
return creditHours;
public
{{ }}
System.out.println("Name: :"+name);
System.out.println("Name "+name); }}
System.out.println("CreditHours
System.out.println("Credit Hours: :"+
"+creditHours);
creditHours);
}}
Example: Class Department
Implementation of Class Department
importjava.io.*;
import java.io.*; publicvoid
voidsetDepartment()
setDepartment()
public
importjava.util.Scanner;
java.util.Scanner;
import {{
publicclass
public classDepartment
Department Scannerinput
input==new
newScanner(System.in);
Scanner(System.in);
Scanner
{{ System.out.print("Pleaseenter
System.out.print("Please enterthe
thename
nameofofDepartment
Department:");
:");
privateString
private Stringname;
name; name=input.next()+input.nextLine();
=input.next()+input.nextLine();
name
privateCourse
private Course[]c;
[]c; for(int
(inti=0;
i=0;i<c.length;
i<c.length;i++)
i++)
for
publicDepartment(int
Department(intsize)
size)
public {{
{{ System.out.print("Pleaseenter
System.out.print("Please enterthe
thename
nameofofthe
thecourse
course:");
:");
name=""";";
name= c[i]=newcourse();
course();
c[i]=new
c=new
c= newCourse[size];
Course[size]; c[i].setName(input.next()+input.nextLine());
input.nextLine());
c[i].setName(input.next()+
}} System.out.print("Pleaseenter
System.out.print("Please enterthe
thecredit
credithours
hours: :");
");
c[i].setCreditHs(input.nextInt());
c[i].setCreditHs(input.nextInt());
}}
}}
Example: Class Department
Implementation of Class Department
publicvoid
public voidopenInputFile(String
openInputFile(StringfileName)
fileName)throws
throws
publicvoid
public voidopenOutputFile(String
openOutputFile(StringfileName)
fileName)throws
throws ClassNotFoundException,IOException
ClassNotFoundException, IOException
IOException
IOException
{{
{{ File f f==new
newFile(fileName);
File(fileName);
File
File f f==new
File newFile(fileName);
File(fileName);
FileInputStream gg==new
FileInputStream newFileInputStream(f);
FileInputStream(f);
FileOutputStream gg==new
FileOutputStream newFileOutputStream(f);
FileOutputStream(f);
ObjectInputStreamobj
ObjectInputStream obj==new
newObjectInputStream(g);
ObjectInputStream(g);
ObjectOutputStreamobj
ObjectOutputStream obj==new
newObjectOutputStream(g);
ObjectOutputStream(g);
name=obj.readLine();
name=obj.readLine();
obj.writeBytes(name);
obj.writeBytes(name);
cc==(Course
(Course[])obj.readObject();
[])obj.readObject();
obj.writeObject(c);
obj.writeObject(c); obj.close();
obj.close();
obj.close();
obj.close();
}}
}}
Example: Class Department
Implementation of Class Department
publicdouble
public doubleaverageCredit()
averageCredit()
{{
doubles=0.0;
double s=0.0;
for(int
for (inti=0;
i=0;i<c.length;
i<c.length;i++)
i++)
s+=c[i].getCreditHours();
s+=c[i].getCreditHours();
return(s/c.length);
return (s/c.length);
}}
publicvoid
public voiddisplay()
display()
{{
System.out.println("========================");
System.out.println("========================");
System.out.println("Thename
System.out.println("The nameofofthe
thedepartment
departmentisis:":"++name);
name);
for(int
for (inti=0;
i=0;i<c.length;
i<c.length;i++)
i++)
c[i].display();
c[i].display();
System.out.println("Theaverage
System.out.println("The averageofofcredit
credithours
hoursisis:":"++averageCredit());
averageCredit());
}}
}}
Implementation of DepartmentTest1
importjava.io.*;
import java.io.*; /*/* run
run
publicclass
public classDepartmentTest1
DepartmentTest1 Pleaseenter
Please enterthe
thename
nameofofDepartment
Department:Computer
:Computerscience
science
Pleaseenter
enterthe
thename
nameofofthe
thecourse
course:csc107
:csc107
{{ Please
publicstatic
staticvoid
voidmain(String[]
main(String[]args)
args)throws
throwsIOException
IOException Pleaseenter
Please enterthe
thecredit
credithours
hours: :33
public
Pleaseenter
enterthe
thename
nameofofthe
thecourse
course:csc112
:csc112
{{ Please
Departmentdep
Department dep==new
newDepartment(3);
Department(3); Pleaseenter
Please enterthe
thecredit
credithours
hours: :33
dep.setDepartment(); Pleaseenter
Please enterthe
thename
nameofofthe
thecourse
course:csc113
:csc113
dep.setDepartment();
dep.openOutputFile("computer.data"); Pleaseenter
Please enterthe
thecredit
credithours
hours: :44
dep.openOutputFile("computer.data");
Departmentdep2
dep2==new
newDepartment(2);
Department(2); Pleaseenter
Please enterthe
thename
nameofofDepartment
Department:Engineering
:Engineering
Department
dep2.setDepartment();
dep2.setDepartment(); Pleaseenter
Please enterthe
thename
nameofofthe
thecourse
course:eng123
:eng123
dep2.openOutputFile("engineering.data"); Pleaseenter
Please enterthe
thecredit
credithours
hours: :44
dep2.openOutputFile("engineering.data");
Pleaseenter
enterthe
thename
nameofofthe
thecourse
course:eng125
:eng125
}} Please
Pleaseenter
enterthe
thecredit
credithours
hours: :33
}} Please
*/*/
Implementation of DepartmentTest2
importjava.io.*;
java.io.*;
import /*/*
publicclass
public classDepartmentTest2
DepartmentTest2 ======================================
======================================
{{ Thename
The nameofofthe
thedepartment
departmentisis:Computer
:Computerscience
science
publicstatic
public staticvoid
voidmain(String[]
main(String[]args)
args)throws
throws Name: :csc107
csc107
Name
ClassNotFoundException,IOException
ClassNotFoundException, IOException CreditHours
Hours: :33
Credit
{{ Name: :csc112
Name csc112
Departmentd1
Department d1==new
newDepartment(3);
Department(3); CreditHours
Hours: :33
Credit
d1.openInputFile("computer.data");
d1.openInputFile("computer.data"); Name: :csc113
csc113
Name
d1.display();
d1.display(); CreditHours
Hours: :44
Credit
Departmentd2
Department d2==new
newDepartment(2);
Department(2); Theaverage
averageofofcredit
credithours
hoursisis:3.3333333333333335
:3.3333333333333335
The
d2.openInputFile("engineering.data");
d2.openInputFile("engineering.data"); ======================================
======================================
d2.display();
d2.display(); Thename
nameofofthe
thedepartment
departmentisis:Engineering
:Engineering
The
}} Name: :eng123
Name eng123
}} CreditHours
Credit Hours: :44
Name: :eng125
Name eng125
CreditHours
Credit Hours: :33
Theaverage
The averageofofcredit
credithours
hoursisis:3.5
:3.5
*/*/