SlideShare a Scribd company logo
Chapter 12 File Input and Output
Chapter 12 Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The File Class ,[object Object],Opens the file  sample.dat  in the current directory. Opens the file  test.dat  in the directory C:amplePrograms 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:avaProjectsh12  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 ,[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object]
12.2 Low-Level File I/O ,[object Object],[object Object],[object Object],[object Object]
Streams for Low-Level File I/O ,[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object]
Setting up DataOutputStream ,[object 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 ,[object 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 ,[object Object]
Textfile Input and Output ,[object Object],[object Object],[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 ,[object Object],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 ,[object Object],[object Object]
Development Steps ,[object Object],[object Object],[object Object],[object Object],[object Object]
Step 1 Design ,[object Object],[object Object]
Step 1 Code ,[object Object],[object Object],[object Object],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 ,[object Object],[object Object]
Step 2 Design ,[object Object],[object Object],[object Object],[object Object]
Step 2 Code ,[object Object],[object Object],[object Object]
Step 2 Test ,[object Object],[object Object],[object Object],[object Object]
Step 3 Design ,[object Object],[object Object],[object Object]
Step 3 Code ,[object Object],[object Object],[object Object]
Step 3 Test ,[object Object],[object Object],[object Object]
Step 4: Finalize ,[object Object],[object Object]

More Related Content

What's hot

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 
Io streams
Io streamsIo streams
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3sotlsoc
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
babak danyal
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 

What's hot (20)

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Java stream
Java streamJava stream
Java stream
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
 
Io streams
Io streamsIo streams
Io streams
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 

Viewers also liked

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

Viewers also liked (20)

C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Union In language C
Union In language CUnion In language C
Union In language C
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
CP Handout#2
CP Handout#2CP Handout#2
CP Handout#2
 
8.3 program structure (1 hour)
8.3 program structure (1 hour)8.3 program structure (1 hour)
8.3 program structure (1 hour)
 
CP Handout#5
CP Handout#5CP Handout#5
CP Handout#5
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]
 
Apclass
ApclassApclass
Apclass
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
 
Chapter 2 - Structure of C++ Program
Chapter 2 - Structure of C++ ProgramChapter 2 - Structure of C++ Program
Chapter 2 - Structure of C++ Program
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Loop c++
Loop c++Loop c++
Loop c++
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Array in c++
Array in c++Array in c++
Array in c++
 

Similar to Chapter 12 - File Input and Output

File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
shahidqamar17
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
SakhilejasonMsibi
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
Janu Jahnavi
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
PRABHATMISHRA969924
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
suraj pandey
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
NavneetSheoran3
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++Teguh Nugraha
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 

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

File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
5java Io
5java Io5java Io
5java Io
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 

More from Eduardo Bergavera

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian Family
Eduardo Bergavera
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 

More from Eduardo Bergavera (9)

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian Family
 
What is Python?
What is Python?What is Python?
What is Python?
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software Development
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 

Chapter 12 - File Input and Output

  • 1. Chapter 12 File Input and Output
  • 2.
  • 3.
  • 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:avaProjectsh12 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.
  • 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.
  • 8.
  • 9.
  • 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.
  • 13.
  • 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.
  • 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.
  • 18.
  • 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.
  • 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.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.

Editor's Notes

  1. 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.
  2. 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 )) ;
  3. 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.
  4. 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.
  5. 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.
  6. 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(); } }
  7. You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( 15 ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( &apos;X&apos; );
  8. You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( 15 ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( &apos;X&apos; );
  9. 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; } } }
  10. Please use your Java IDE to view the source files and run the program.
  11. 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.