SlideShare a Scribd company logo
Chapter 12 File Input and Output
Chapter 12 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 Read a text file using Scanner Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream
The File Class To operate on a file, we must first create a  File  object (from  java.io ).  Opens the file  sample.dat  in the current directory. Opens the file  test.dat  in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.  File inFile = new File(“sample.dat”);  File inFile = new File (“C:/SamplePrograms/test.dat”);
Some File Methods To see if  inFile  is associated to a real file correctly. To see if  inFile  is associated to a file or not. If false, it is a directory. List the name of all files in the directory C:\JavaProjects\Ch12  if   (  inFile.exists ( ) ) { if   (  inFile.isFile () ) {   File directory =  new     File ( &quot;C:/JavaPrograms/Ch12&quot; ) ; String filename []  = directory.list () ; for   ( int   i = 0; i < filename.length; i++ ) { System.out.println ( filename [ i ]) ; }
The  JFileChooser  Class A  javax.swing.JFileChooser  object allows the user to select a file. To start the listing from a specific directory: JFileChooser chooser =  new   JFileChooser ( ) ; chooser.showOpenDialog ( null ) ; JFileChooser chooser =  new   JFileChooser ( &quot;D:/JavaPrograms/Ch12&quot; ) ; chooser.showOpenDialog ( null ) ;
Getting Info from JFileChooser int   status = chooser.showOpenDialog ( null ) ; if   ( status == JFileChooser.APPROVE_OPTION ) { JOptionPane.showMessageDialog ( null ,  &quot;Open is clicked&quot; ) ; }  else   {  //== JFileChooser.CANCEL_OPTION JOptionPane.showMessageDialog ( null ,  &quot;Cancel is clicked&quot; ) ; } File selectedFile  = chooser.getSelectedFile () ; File currentDirectory = chooser.getCurrentDirectory () ;
Applying a File Filter A  file filter  may be used to restrict the listing in JFileChooser to only those files/directories that meet the designated filtering criteria. To apply a file, we define a subclass of the  javax.swing.filechooser.FileFilter  class and provide the  accept  and  getDescription  methods. public boolean  accept ( File file ) public String  getDescription ( ) See the JavaFilter class that restricts the listing to directories and Java source files.
12.2 Low-Level File I/O To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file. A  stream  is a sequence of data items, usually 8-bit bytes. Java has two types of streams: an  input stream  and an  output stream .  An  input stream  has a source form which the data items come, and an  output stream  has a destination to which the data items are going.
Streams for Low-Level File I/O FileOutputStream  and  FileInputStream  are two stream objects that facilitate file access. FileOutputStream  allows us to output a sequence of bytes; values of data type  byte . FileInputStream  allows us to read in an array of bytes.
Sample: Low-Level File Output  //set up file and stream File  outFile  =  new  File ( &quot;sample1.data&quot; ) ; FileOutputStream  outStream =  new  FileOutputStream (  outFile  ) ; //data to save byte []  byteArray =  { 10, 20, 30, 40,    50, 60, 70, 80 } ; //write data to the stream outStream.write (  byteArray  ) ; //output done, so close the stream outStream.close () ;
Sample: Low-Level File Input  //set up file and stream File  inFile   =  new  File ( &quot;sample1.data&quot; ) ; FileInputStream inStream =  new  FileInputStream ( inFile ) ; //set up an array to read data in int   fileSize  =  ( int ) inFile.length () ; byte []  byteArray =  new  byte [ fileSize ] ; //read data in and display them inStream.read ( byteArray ) ; for   ( int  i = 0; i < fileSize; i++ ) { System.out.println ( byteArray [ i ]) ; } //input done, so close the stream inStream.close () ;
Streams for High-Level File I/O FileOutputStream and DataOutputStream are used to output primitive data values FileInputStream and DataInputStream are used to input primitive data values To read the data back correctly, we must know the order of the data stored and their data types
Setting up DataOutputStream A standard sequence to set up a DataOutputStream object:
Sample Output import   java.io.*; class   Ch12TestDataOutputStream  { public static void   main  ( String []  args )  throws   IOException  { . . .  //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt ( 987654321 ) ; outDataStream.writeLong ( 11111111L ) ; outDataStream.writeFloat ( 22222222F ) ; outDataStream.writeDouble ( 3333333D ) ; outDataStream.writeChar ( 'A' ) ; outDataStream.writeBoolean ( true ) ; //output done, so close the stream outDataStream.close () ; } }
Setting up DataInputStream A standard sequence to set up a DataInputStream object:
Sample Input import   java.io.*; class   Ch12TestDataInputStream  { public static void   main  ( String []  args )  throws   IOException  { . . .  //set up inDataStream //read values back from the stream and display them System.out.println ( inDataStream.readInt ()) ; System.out.println ( inDataStream.readLong ()) ; System.out.println ( inDataStream.readFloat ()) ; System.out.println ( inDataStream.readDouble ()) ; System.out.println ( inDataStream.readChar ()) ; System.out.println ( inDataStream.readBoolean ()) ; //input done, so close the stream inDataStream.close () ; } }
Reading Data Back in Right Order The order of write and read operations must match in order to read the stored primitive data back correctly.
Textfile Input and Output Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. This allows us to view the file content using any text editor To output data as a string to file, we use a PrintWriter object To input data from a textfile, we use FileReader and BufferedReader classes From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting textfiles
Sample Textfile Output import   java.io.*; class   Ch12TestPrintWriter  { public static void   main  ( String []  args )  throws   IOException  { //set up file and stream File outFile =  new   File ( &quot;sample3.data&quot; ) ; FileOutputStream outFileStream  =  new   FileOutputStream ( outFile ) ; PrintWriter outStream =  new   PrintWriter ( outFileStream ) ; //write values of primitive data types to the stream outStream.println ( 987654321 ) ; outStream.println ( &quot;Hello, world.&quot; ) ; outStream.println ( true ) ; //output done, so close the stream outStream.close () ; } }
Sample Textfile Input import   java.io.*; class   Ch12TestBufferedReader  { public static void   main  ( String []  args )  throws   IOException  { //set up file and stream File inFile =  new   File ( &quot;sample3.data&quot; ) ; FileReader fileReader =  new   FileReader ( inFile ) ; BufferedReader bufReader =  new   BufferedReader ( fileReader ) ; String str; str = bufReader.readLine () ; int   i = Integer.parseInt ( str ) ; //similar process for other data types bufReader.close () ; } }
Sample Textfile Input with Scanner import   java.io.*; class   Ch12TestScanner  { public static void   main  ( String []  args )  throws   IOException  { //open the Scanner Scanner scanner =  new  Scanner ( new   File ( &quot;sample3.data&quot; )) ; //get integer int  i = scanner.nextInt () ; //similar process for other data types scanner.close () ; } }
Object File I/O It is possible to store objects just as easily as you store primitive data values. We use  ObjectOutputStream  and  ObjectInputStream  to save to and load objects from a file. To save objects from a given class, the class declaration must include the phrase  implements Serializable . For example, class  Person  implements  Serializable  { . . . }
Saving Objects Could save objects from the different classes. File outFile  =  new  File ( &quot;objects.data&quot; ) ; FileOutputStream  outFileStream  =  new  FileOutputStream ( outFile ) ; ObjectOutputStream outObjectStream =  new  ObjectOutputStream ( outFileStream ) ; Person person =  new  Person ( &quot;Mr. Espresso&quot; , 20,  'M' ) ; outObjectStream.writeObject (  person  ) ; account1 = new Account () ; bank1   = new Bank () ; outObjectStream.writeObject (  account1  ) ; outObjectStream.writeObject (  bank1  ) ;
Reading Objects Must read in the correct order. Must type cast to the correct object type. File inFile  =  new  File ( &quot;objects.data&quot; ) ; FileInputStream  inFileStream  =  new  FileInputStream ( inFile ) ; ObjectInputStream inObjectStream =  new  ObjectInputStream ( inFileStream ) ; Person person  =  ( Person )  inObjectStream.readObject ( ) ; Account account1 =  ( Account )  inObjectStream.readObject ( ) ; Bank  bank1     =  ( Bank )  inObjectStream.readObject ( ) ;
Saving and Loading Arrays Instead of processing array elements individually, it is possible to save and load the whole array at once. Person []  people =  new  Person [  N  ] ;  //assume N already has a value //build the people array . . . //save the array outObjectStream.writeObject  (  people  ) ; //read the array Person [ ]  people =  ( Person [])  inObjectStream.readObject ( ) ;
Problem Statement Problem statement: Write a class that manages file I/O of an AddressBook object.
Development Steps We will develop this program in four steps: Implement the constructor and the setFile method. Implement the write method. Implement the read method. Finalize the class.
Step 1 Design We identify the data members and define a constructor to initialize them. Instead of storing individual Person objects, we will deal with a AddressBook object directly using Object I/O techniques.
Step 1 Code Directory:   Chapter12/Step1 Source Files:  AddressBookStorage.java TestAddressBookStorage.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
Step 1 Test We include a temporary output statement inside the setFile method. We run the test main class and verify that the setFile method is called correctly.
Step 2 Design Design and implement the  write  method The data member filename stores the name of the object file to store the address book.  We create an ObjectOutputStream object from the data member filename in the  write  method. The  write  method will propagate an IOException when one is thrown.
Step 2 Code Directory:   Chapter12/Step2 Source Files:  AddressBookStorage.java TestAddressBookWrite.java
Step 2 Test We run the test program several times with different sizes for the address book. We verify that the resulting files indeed have different sizes. At this point, we cannot check whether the data are saved correctly or not. We can do so only after finishing the code to read the data back.
Step 3 Design Design and implement the  read  method. The method returns an AddressBook object read from a file (if there's no exception) The method will propagate an IOException when one is thrown.
Step 3 Code Directory:   Chapter12/Step3 Source Files:  AddressBookStorage.java TestAddressBookRead.java
Step 3 Test We will write a test program to verify that the data can be read back correctly from a file. To test the read operation, the file to read the data from must already exist.  We will make this test program save the data first by using the TestAddressBookWrite class from .
Step 4: Finalize We perform the critical review of the final program. We run the final test

More Related Content

PPT
File Input & Output
PRN USM
 
PDF
Java I/O
Jussi Pohjolainen
 
PDF
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
PPTX
Java file
sonnetdp
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPTX
Understanding java streams
Shahjahan Samoon
 
PDF
Java IO
UTSAB NEUPANE
 
PPTX
Handling I/O in Java
Hiranya Jayathilaka
 
File Input & Output
PRN USM
 
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
Java file
sonnetdp
 
Java I/o streams
Hamid Ghorbani
 
Understanding java streams
Shahjahan Samoon
 
Java IO
UTSAB NEUPANE
 
Handling I/O in Java
Hiranya Jayathilaka
 

What's hot (20)

PDF
Java - File Input Output Concepts
Victer Paul
 
PPT
Java stream
Arati Gadgil
 
PDF
I/O in java Part 1
ashishspace
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PPTX
L21 io streams
teach4uin
 
PPS
Files & IO in Java
CIB Egypt
 
ODP
IO In Java
parag
 
PPTX
Java Input Output (java.io.*)
Om Ganesh
 
PPT
Java căn bản - Chapter12
Vince Vo
 
PPT
7 streams and error handling in java
Jyoti Verma
 
PPTX
Io streams
Elizabeth alexander
 
PDF
32.java input-output
santosh mishra
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
Input output files in java
Kavitha713564
 
PPT
Input output streams
Parthipan Parthi
 
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PPTX
Chapter 10.3
sotlsoc
 
PPT
Java IO Package and Streams
babak danyal
 
PDF
java.io - streams and files
Marcello Thiry
 
Java - File Input Output Concepts
Victer Paul
 
Java stream
Arati Gadgil
 
I/O in java Part 1
ashishspace
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
L21 io streams
teach4uin
 
Files & IO in Java
CIB Egypt
 
IO In Java
parag
 
Java Input Output (java.io.*)
Om Ganesh
 
Java căn bản - Chapter12
Vince Vo
 
7 streams and error handling in java
Jyoti Verma
 
32.java input-output
santosh mishra
 
Multithreading in java
Kavitha713564
 
Input output files in java
Kavitha713564
 
Input output streams
Parthipan Parthi
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Java Streams
M Vishnuvardhan Reddy
 
Chapter 10.3
sotlsoc
 
Java IO Package and Streams
babak danyal
 
java.io - streams and files
Marcello Thiry
 
Ad

Viewers also liked (20)

PPT
C Structures And Unions
Ram Sagar Mourya
 
PPT
Union In language C
Ravi Singh
 
PPT
cpp input & output system basics
gourav kottawar
 
PPT
Chapter 13 - Inheritance and Polymorphism
Eduardo Bergavera
 
PDF
CP Handout#2
trupti1976
 
PPT
8.3 program structure (1 hour)
akmalfahmi
 
PDF
CP Handout#5
trupti1976
 
PPTX
Constructs (Programming Methodology)
Jyoti Bhardwaj
 
DOC
Java programming lab assignments
rajni kaushal
 
PPTX
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
PPT
Apclass
geishaannealagos
 
PPT
Apclass (2)
geishaannealagos
 
PDF
Chapter 2 - Structure of C++ Program
Deepak Singh
 
PPTX
C++ lecture 04
HNDE Labuduwa Galle
 
PPTX
Loop c++
Mood Mood
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
C++ programming (Array)
طارق بالحارث
 
PPT
User defined functions in C programmig
Appili Vamsi Krishna
 
PPTX
Stream classes in C++
Shyam Gupta
 
PPTX
Array in c++
Mahesha Mano
 
C Structures And Unions
Ram Sagar Mourya
 
Union In language C
Ravi Singh
 
cpp input & output system basics
gourav kottawar
 
Chapter 13 - Inheritance and Polymorphism
Eduardo Bergavera
 
CP Handout#2
trupti1976
 
8.3 program structure (1 hour)
akmalfahmi
 
CP Handout#5
trupti1976
 
Constructs (Programming Methodology)
Jyoti Bhardwaj
 
Java programming lab assignments
rajni kaushal
 
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
Apclass (2)
geishaannealagos
 
Chapter 2 - Structure of C++ Program
Deepak Singh
 
C++ lecture 04
HNDE Labuduwa Galle
 
Loop c++
Mood Mood
 
Union in C programming
Kamal Acharya
 
C++ programming (Array)
طارق بالحارث
 
User defined functions in C programmig
Appili Vamsi Krishna
 
Stream classes in C++
Shyam Gupta
 
Array in c++
Mahesha Mano
 
Ad

Similar to Chapter 12 - File Input and Output (20)

PDF
Lecture 11.pdf
SakhilejasonMsibi
 
PDF
Programming language JAVA Input output opearations
2025183005
 
PPT
File Input and Output in Java Programing language
BurhanKhan774154
 
PDF
Java Day-6
People Strategists
 
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
PPTX
IOStream.pptx
HindAlmisbahi
 
PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
PDF
Java IO Stream, the introduction to Streams
ranganadh6
 
PPTX
File Handling.pptx
PragatiSutar4
 
PPTX
File Input and output.pptx
cherryreddygannu
 
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
PPT
Comp102 lec 11
Fraz Bakhsh
 
PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PPT
Java Input Output and File Handling
Sunil OS
 
PDF
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
PPTX
Input/Output Exploring java.io
NilaNila16
 
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
PPTX
File Handling in Java Oop presentation
Azeemaj101
 
PPTX
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Lecture 11.pdf
SakhilejasonMsibi
 
Programming language JAVA Input output opearations
2025183005
 
File Input and Output in Java Programing language
BurhanKhan774154
 
Java Day-6
People Strategists
 
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
IOStream.pptx
HindAlmisbahi
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
Java IO Stream, the introduction to Streams
ranganadh6
 
File Handling.pptx
PragatiSutar4
 
File Input and output.pptx
cherryreddygannu
 
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
Comp102 lec 11
Fraz Bakhsh
 
File Handling in Java.pdf
SudhanshiBakre1
 
Java Input Output and File Handling
Sunil OS
 
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Input/Output Exploring java.io
NilaNila16
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
File Handling in Java Oop presentation
Azeemaj101
 
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 

More from Eduardo Bergavera (9)

PPTX
CLP Session 5 - The Christian Family
Eduardo Bergavera
 
PDF
What is Python?
Eduardo Bergavera
 
PPT
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
PPT
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
PPT
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
PPT
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
PPT
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
PPT
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
PPT
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 
CLP Session 5 - The Christian Family
Eduardo Bergavera
 
What is Python?
Eduardo Bergavera
 
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 

Recently uploaded (20)

PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Software Development Company | KodekX
KodekX
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Software Development Methodologies in 2025
KodekX
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
This slide provides an overview Technology
mineshkharadi333
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 

Chapter 12 - File Input and Output

  • 1. Chapter 12 File Input and Output
  • 2. Chapter 12 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 Read a text file using Scanner Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream
  • 3. The File Class To operate on a file, we must first create a File object (from java.io ). Opens the file sample.dat in the current directory. Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname. File inFile = new File(“sample.dat”); File inFile = new File (“C:/SamplePrograms/test.dat”);
  • 4. Some File Methods To see if inFile is associated to a real file correctly. To see if inFile is associated to a file or not. If false, it is a directory. List the name of all files in the directory C:\JavaProjects\Ch12 if ( inFile.exists ( ) ) { if ( inFile.isFile () ) { File directory = new File ( &quot;C:/JavaPrograms/Ch12&quot; ) ; String filename [] = directory.list () ; for ( int i = 0; i < filename.length; i++ ) { System.out.println ( filename [ i ]) ; }
  • 5. The JFileChooser Class A javax.swing.JFileChooser object allows the user to select a file. To start the listing from a specific directory: JFileChooser chooser = new JFileChooser ( ) ; chooser.showOpenDialog ( null ) ; JFileChooser chooser = new JFileChooser ( &quot;D:/JavaPrograms/Ch12&quot; ) ; chooser.showOpenDialog ( null ) ;
  • 6. Getting Info from JFileChooser int status = chooser.showOpenDialog ( null ) ; if ( status == JFileChooser.APPROVE_OPTION ) { JOptionPane.showMessageDialog ( null , &quot;Open is clicked&quot; ) ; } else { //== JFileChooser.CANCEL_OPTION JOptionPane.showMessageDialog ( null , &quot;Cancel is clicked&quot; ) ; } File selectedFile = chooser.getSelectedFile () ; File currentDirectory = chooser.getCurrentDirectory () ;
  • 7. Applying a File Filter A file filter may be used to restrict the listing in JFileChooser to only those files/directories that meet the designated filtering criteria. To apply a file, we define a subclass of the javax.swing.filechooser.FileFilter class and provide the accept and getDescription methods. public boolean accept ( File file ) public String getDescription ( ) See the JavaFilter class that restricts the listing to directories and Java source files.
  • 8. 12.2 Low-Level File I/O To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file. A stream is a sequence of data items, usually 8-bit bytes. Java has two types of streams: an input stream and an output stream . An input stream has a source form which the data items come, and an output stream has a destination to which the data items are going.
  • 9. Streams for Low-Level File I/O FileOutputStream and FileInputStream are two stream objects that facilitate file access. FileOutputStream allows us to output a sequence of bytes; values of data type byte . FileInputStream allows us to read in an array of bytes.
  • 10. Sample: Low-Level File Output //set up file and stream File outFile = new File ( &quot;sample1.data&quot; ) ; FileOutputStream outStream = new FileOutputStream ( outFile ) ; //data to save byte [] byteArray = { 10, 20, 30, 40, 50, 60, 70, 80 } ; //write data to the stream outStream.write ( byteArray ) ; //output done, so close the stream outStream.close () ;
  • 11. Sample: Low-Level File Input //set up file and stream File inFile = new File ( &quot;sample1.data&quot; ) ; FileInputStream inStream = new FileInputStream ( inFile ) ; //set up an array to read data in int fileSize = ( int ) inFile.length () ; byte [] byteArray = new byte [ fileSize ] ; //read data in and display them inStream.read ( byteArray ) ; for ( int i = 0; i < fileSize; i++ ) { System.out.println ( byteArray [ i ]) ; } //input done, so close the stream inStream.close () ;
  • 12. Streams for High-Level File I/O FileOutputStream and DataOutputStream are used to output primitive data values FileInputStream and DataInputStream are used to input primitive data values To read the data back correctly, we must know the order of the data stored and their data types
  • 13. Setting up DataOutputStream A standard sequence to set up a DataOutputStream object:
  • 14. Sample Output import java.io.*; class Ch12TestDataOutputStream { public static void main ( String [] args ) throws IOException { . . . //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt ( 987654321 ) ; outDataStream.writeLong ( 11111111L ) ; outDataStream.writeFloat ( 22222222F ) ; outDataStream.writeDouble ( 3333333D ) ; outDataStream.writeChar ( 'A' ) ; outDataStream.writeBoolean ( true ) ; //output done, so close the stream outDataStream.close () ; } }
  • 15. Setting up DataInputStream A standard sequence to set up a DataInputStream object:
  • 16. Sample Input import java.io.*; class Ch12TestDataInputStream { public static void main ( String [] args ) throws IOException { . . . //set up inDataStream //read values back from the stream and display them System.out.println ( inDataStream.readInt ()) ; System.out.println ( inDataStream.readLong ()) ; System.out.println ( inDataStream.readFloat ()) ; System.out.println ( inDataStream.readDouble ()) ; System.out.println ( inDataStream.readChar ()) ; System.out.println ( inDataStream.readBoolean ()) ; //input done, so close the stream inDataStream.close () ; } }
  • 17. Reading Data Back in Right Order The order of write and read operations must match in order to read the stored primitive data back correctly.
  • 18. Textfile Input and Output Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. This allows us to view the file content using any text editor To output data as a string to file, we use a PrintWriter object To input data from a textfile, we use FileReader and BufferedReader classes From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting textfiles
  • 19. Sample Textfile Output import java.io.*; class Ch12TestPrintWriter { public static void main ( String [] args ) throws IOException { //set up file and stream File outFile = new File ( &quot;sample3.data&quot; ) ; FileOutputStream outFileStream = new FileOutputStream ( outFile ) ; PrintWriter outStream = new PrintWriter ( outFileStream ) ; //write values of primitive data types to the stream outStream.println ( 987654321 ) ; outStream.println ( &quot;Hello, world.&quot; ) ; outStream.println ( true ) ; //output done, so close the stream outStream.close () ; } }
  • 20. Sample Textfile Input import java.io.*; class Ch12TestBufferedReader { public static void main ( String [] args ) throws IOException { //set up file and stream File inFile = new File ( &quot;sample3.data&quot; ) ; FileReader fileReader = new FileReader ( inFile ) ; BufferedReader bufReader = new BufferedReader ( fileReader ) ; String str; str = bufReader.readLine () ; int i = Integer.parseInt ( str ) ; //similar process for other data types bufReader.close () ; } }
  • 21. Sample Textfile Input with Scanner import java.io.*; class Ch12TestScanner { public static void main ( String [] args ) throws IOException { //open the Scanner Scanner scanner = new Scanner ( new File ( &quot;sample3.data&quot; )) ; //get integer int i = scanner.nextInt () ; //similar process for other data types scanner.close () ; } }
  • 22. Object File I/O It is possible to store objects just as easily as you store primitive data values. We use ObjectOutputStream and ObjectInputStream to save to and load objects from a file. To save objects from a given class, the class declaration must include the phrase implements Serializable . For example, class Person implements Serializable { . . . }
  • 23. Saving Objects Could save objects from the different classes. File outFile = new File ( &quot;objects.data&quot; ) ; FileOutputStream outFileStream = new FileOutputStream ( outFile ) ; ObjectOutputStream outObjectStream = new ObjectOutputStream ( outFileStream ) ; Person person = new Person ( &quot;Mr. Espresso&quot; , 20, 'M' ) ; outObjectStream.writeObject ( person ) ; account1 = new Account () ; bank1 = new Bank () ; outObjectStream.writeObject ( account1 ) ; outObjectStream.writeObject ( bank1 ) ;
  • 24. Reading Objects Must read in the correct order. Must type cast to the correct object type. File inFile = new File ( &quot;objects.data&quot; ) ; FileInputStream inFileStream = new FileInputStream ( inFile ) ; ObjectInputStream inObjectStream = new ObjectInputStream ( inFileStream ) ; Person person = ( Person ) inObjectStream.readObject ( ) ; Account account1 = ( Account ) inObjectStream.readObject ( ) ; Bank bank1 = ( Bank ) inObjectStream.readObject ( ) ;
  • 25. Saving and Loading Arrays Instead of processing array elements individually, it is possible to save and load the whole array at once. Person [] people = new Person [ N ] ; //assume N already has a value //build the people array . . . //save the array outObjectStream.writeObject ( people ) ; //read the array Person [ ] people = ( Person []) inObjectStream.readObject ( ) ;
  • 26. Problem Statement Problem statement: Write a class that manages file I/O of an AddressBook object.
  • 27. Development Steps We will develop this program in four steps: Implement the constructor and the setFile method. Implement the write method. Implement the read method. Finalize the class.
  • 28. Step 1 Design We identify the data members and define a constructor to initialize them. Instead of storing individual Person objects, we will deal with a AddressBook object directly using Object I/O techniques.
  • 29. Step 1 Code Directory: Chapter12/Step1 Source Files: AddressBookStorage.java TestAddressBookStorage.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
  • 30. Step 1 Test We include a temporary output statement inside the setFile method. We run the test main class and verify that the setFile method is called correctly.
  • 31. Step 2 Design Design and implement the write method The data member filename stores the name of the object file to store the address book. We create an ObjectOutputStream object from the data member filename in the write method. The write method will propagate an IOException when one is thrown.
  • 32. Step 2 Code Directory: Chapter12/Step2 Source Files: AddressBookStorage.java TestAddressBookWrite.java
  • 33. Step 2 Test We run the test program several times with different sizes for the address book. We verify that the resulting files indeed have different sizes. At this point, we cannot check whether the data are saved correctly or not. We can do so only after finishing the code to read the data back.
  • 34. Step 3 Design Design and implement the read method. The method returns an AddressBook object read from a file (if there's no exception) The method will propagate an IOException when one is thrown.
  • 35. Step 3 Code Directory: Chapter12/Step3 Source Files: AddressBookStorage.java TestAddressBookRead.java
  • 36. Step 3 Test We will write a test program to verify that the data can be read back correctly from a file. To test the read operation, the file to read the data from must already exist. We will make this test program save the data first by using the TestAddressBookWrite class from .
  • 37. Step 4: Finalize We perform the critical review of the final program. We run the final test

Editor's Notes

  • #4: When a program that manipulates a large amount of data practical, we must save the data to a file. If we don’t, then the user must reenter the same data every time he or she runs the program because any data used by the program will be erased from the main memory at program termination. If the data were saved, then the program can read them back from the file and rebuild the information so the user can work on the data without reentering them. In this chapter you will learn how to save data to and read data from a file. We call the action of saving data to a file file output and the action of reading data from a file file input . Note: The statements new File( “C:\SamplePrograms”, “one.txt”); and new File(“C:\SamplePrograms\one.text”); will open the same file.
  • #6: We can start the listing from a current directory by writing String current = System.getProperty ( &amp;quot;user.dir&amp;quot; ) ; JFileChooser chooser = new JFileChooser ( current ) ; or equivalently String current = System.getProperty ( &amp;quot;user.dir&amp;quot; ) ; JFileChooser chooser = new JFileChooser ( ) ; chooser.setCurrentDirectory ( new File ( current )) ;
  • #8: The accept method returns true if the parameter file is a file to be included in the list. The getDescription method returns a text that will be displayed as one of the entries for the “Files of Type:” drop-down list.
  • #10: Data is saved in blocks of bytes to reduce the time it takes to save all of our data. The operation of saving data as a block is called data caching . To carry out data caching, part of memory is reserved as a data buffer or cache , which is used as a temporary holding place. Data are first written to a buffer. When the buffer becomes full, the data in the buffer are actually written to a file. If there are any remaining data in the buffer and the file is not closed, those data will be lost.
  • #11: class TestFileOutputStream { public static void main (String[] args) throws IOException { //set up file and stream File outFile = new File(&amp;quot;sample1.data&amp;quot;); FileOutputStream outStream = new FileOutputStream(outFile); //data to output byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write(byteArray); //output done, so close the stream outStream.close(); } } The main method throws an exception. Exception handling is described in Section 11.4.
  • #12: import javabook.*; import java.io.*; class TestFileInputStream { public static void main (String[] args) throws IOException { MainWindow mainWindow = new MainWindow(); OutputBox outputBox = new OutputBox(mainWindow); mainWindow.setVisible( true ); outputBox.setVisible( true ); //set up file and stream File inFile = new File(&amp;quot;sample1.data&amp;quot;); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i &lt; fileSize; i++) { outputBox.printLine(byteArray[i]); } //input done, so close the stream inStream.close(); } }
  • #24: You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( 15 ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( &apos;X&apos; );
  • #25: You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( 15 ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( &apos;X&apos; );
  • #26: class FindSum { private int sum; private boolean success; public int getSum() { return sum; } public boolean isSuccess() { return success; } void computeSum (String fileName ) { success = true; try { File inFile = new File(fileName); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); //read three integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); } catch (IOException e) { success = false; } } }
  • #30: Please use your Java IDE to view the source files and run the program.
  • #35: Here&apos;s the pseudocode to locate a person with the designated name. Notice that for this routine to work correctly, the array must be packed with the real pointers in the first half and null pointers in the last half.