SlideShare una empresa de 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]

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a Java căn bản - Chapter12

Similar 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
 

Más 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
 

Más 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

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 

Último (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .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 del 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.