SlideShare uma empresa Scribd logo
1 de 37
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]

Mais conteúdo relacionado

Mais procurados

IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingGurpreet singh
 
Web scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabsWeb scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabszekeLabs Technologies
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserializationYoung Alista
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NETAbhi Arya
 
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 StreamsAnton Keks
 
Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object SerializationNavneet Prakash
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
Serialization in java
Serialization in javaSerialization in java
Serialization in javaJanu Jahnavi
 
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 javaJyoti Verma
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 

Mais procurados (20)

IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
Java file
Java fileJava file
Java file
 
Web scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabsWeb scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabs
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
srgoc
srgocsrgoc
srgoc
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
Java IO
Java IOJava IO
Java IO
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
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
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
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
 
Fast track to lucene
Fast track to luceneFast track to lucene
Fast track to lucene
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 

Destaque

Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2Vince Vo
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 

Destaque (8)

Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Rama Ch14
Rama Ch14Rama Ch14
Rama Ch14
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Rama Ch7
Rama Ch7Rama Ch7
Rama Ch7
 
Rama Ch11
Rama Ch11Rama Ch11
Rama Ch11
 

Semelhante a Java căn bản - Chapter12

Semelhante a Java căn bản - Chapter12 (20)

Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
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
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
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
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
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++
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
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
 

Mais de Vince Vo

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13Vince Vo
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10Vince Vo
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9Vince Vo
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5Vince Vo
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3Vince Vo
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1Vince Vo
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaVince Vo
 

Mais de Vince Vo (19)

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt Java
 
Rama Ch13
Rama Ch13Rama Ch13
Rama Ch13
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Rama Ch10
Rama Ch10Rama Ch10
Rama Ch10
 
Rama Ch8
Rama Ch8Rama Ch8
Rama Ch8
 
Rama Ch9
Rama Ch9Rama Ch9
Rama Ch9
 
Rama Ch6
Rama Ch6Rama Ch6
Rama Ch6
 
Rama Ch5
Rama Ch5Rama Ch5
Rama Ch5
 
Rama Ch4
Rama Ch4Rama Ch4
Rama Ch4
 
Rama Ch3
Rama Ch3Rama Ch3
Rama Ch3
 
Rama Ch2
Rama Ch2Rama Ch2
Rama Ch2
 
Rama Ch1
Rama Ch1Rama Ch1
Rama Ch1
 

Último

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Último (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Java căn bản - Chapter12

  • 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.

Notas do Editor

  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.