SlideShare una empresa de Scribd logo
1 de 28
File Input and Output
Objectives
 After you have read and studied this chapter, you should
be able to
 Use File object to get info about a file
 Include a JFileChooser object in your program to let the user
specify a file.
 Write bytes to a file and read them back from the file, using
FileOutputStream and FileInputStream.
 Write values of primitive data types to a file and read them back
from the file, using DataOutputStream and DataInputStream.
 Write text data to a file and read them back from the file, using
FileWriter,PrintWriter and FileReader,BufferedReader
 Read a text file using Scanner
File
 File is regarded as a collection of bytes
 When a file is read, computer delivers some of
those bytes to the program.
 When a file is written, computer accepts some
bytes from the program and saves them in part
of the file.
 Computer makes no distinction between eg.
image files and text files. Its all bytes to the
hardware. What those bytes are used for is up
to the software.
Types of File
 All information in any file is kept in binary form.
Types of File
 File can be categorized as text (ASCII) file or binary file.
 A text file is a file that contains bytes that represent:
 characters 'A' through 'Z'
 characters 'a' through 'z'
 characters '0' through '9'
 the space character
 punctuation and symbols like . , : ; " + - $ (and others)
 a few control characters that represent end of lines, tabs and some
other things.
using ASCII Codes
 A binary file is a file that contains bytes that represent
others (eg. numbers, image, audio, formatted text etc)
The File Class The File class (from java.io). can be used to obtain info about file
 To do this, we must first create a File object
 A File object can represent a file or a directory
File inFile = new File(“sample.dat”);
File inFile = new File
(“C:/SamplePrograms/test.dat”);
Creates File object for
the file sample.dat in the
current directory.
Creates File object for
the file sample.dat in the
current directory.
Creates File object for
the file test.dat in the
directory
C:SamplePrograms
using the generic file
separator / and
providing the full
pathname.
Creates File object for
the file test.dat in the
directory
C:SamplePrograms
using the generic file
separator / and
providing the full
pathname.
Some File Methods
if ( inFile.exists( ) ) {
if ( inFile.isFile() ) {
File directory = new
File("C:/JavaPrograms/Ch12");
String filename[] = directory.list();
for (int i = 0; i < filename.length; i++) {
System.out.println(filename[i]);
}
To see if inFile is
associated to a real file
correctly.
To see if inFile is
associated to a real file
correctly.
To see if inFile is
associated to a file. If
false, it is a directory.
Also, can test directly if it
is a directory.
To see if inFile is
associated to a file. If
false, it is a directory.
Also, can test directly if it
is a directory.
List the name of all files
in the directory
C:JavaProjectsCh12
List the name of all files
in the directory
C:JavaProjectsCh12
if ( inFile.isDirectory() ) {
Some File Methods
if ( inFile.length( ) ) {
if ( inFile.canRead() ) {
To see the size of the file
in bytes represented by
inFile
To see the size of the file
in bytes represented by
inFile
To see if inFile is
associated to a file that
exist & can be read
To see if inFile is
associated to a file that
exist & can be read
if ( inFile.canWrite() ) { To see if inFile is
associated to a file that
exist & can be written
To see if inFile is
associated to a file that
exist & can be written
if ( inFile.getName() ) { To get the name of the
file represented by inFile
To get the name of the
file represented by inFile
The JFileChooser Class
 A javax.swing.JFileChooser object allows
the user to select a file.
JFileChooser chooser = new JFileChooser( );
chooser.showOpenDialog(null);
JFileChooser chooser = new JFileChooser("D:/JavaPrograms/Ch12");
chooser.showOpenDialog(null);
To start the listing from a specific directory:
The JFileChooser Class
Getting Info from
JFileChooser
int status = chooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "Open is clicked");
} else { //== JFileChooser.CANCEL_OPTION
JOptionPane.showMessageDialog(null, "Cancel is clicked");
}
File selectedFile = chooser.getSelectedFile();
File currentDirectory = chooser.getCurrentDirectory();
I/O Streams
 To read data from or write data to a file,
we must create one of the Java stream
objects and attach it to the file.
 A stream is a sequence of data items,
usually 8-bit bytes.
 Java has two types of streams: an input
stream and an output stream.
 An input stream has a source form
which the data items come, and an
output stream has a destination to which
I/O Streams
I/O Streams
 IO streams are either character-oriented or byte-
oriented.
 Character-oriented IO has special features for
handling character data (text files).
 Byte-oriented IO is for all types of data (binary files)
IO class
Hierarchy
in java.io
package
Streams for Byte –level Binary File I/O
 FileOutputStream and
FileInputStream are two stream objects
that facilitate file access.
 FileOutputStream allows us to output a
sequence of bytes; values of data type
byte.
 FileInputStream allows us to read in an
array of bytes.
Sample: Byte-level Binary
File Output//set up file and stream
File outFile = new File("sample1.data");
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: Byte-level Binary
File Input//set up file and stream
File inFile = new File("sample1.data");
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 Data-Level Binary File I/O
 FileOutputStream and
DataOutputStream are used to output
primitive data values
 FileInputStream and DataInputStream
are used to input primitive data values
 To read the data back correctly, we
must know the order of the data stored
and their data types
Setting up
DataOutputStream A standard sequence to set up a DataOutputStream
object:
Sample Output
import java.io.*;
class Ch12TestDataOutputStream {
public static void main (String[] args) throws IOException {
. . . //set up outDataStream
//write values of primitive data types to the stream
outDataStream.writeInt(987654321);
outDataStream.writeLong(11111111L);
outDataStream.writeFloat(22222222F);
outDataStream.writeDouble(3333333D);
outDataStream.writeChar('A');
outDataStream.writeBoolean(true);
//output done, so close the stream
outDataStream.close();
}
}
Setting up DataInputStream A standard sequence to set up a DataInputStream object:
Sample Input
import java.io.*;
class Ch12TestDataInputStream {
public static void main (String[] args) throws IOException {
. . . //set up inDataStream
//read values back from the stream and display them
System.out.println(inDataStream.readInt());
System.out.println(inDataStream.readLong());
System.out.println(inDataStream.readFloat());
System.out.println(inDataStream.readDouble());
System.out.println(inDataStream.readChar());
System.out.println(inDataStream.readBoolean());
//input done, so close the stream
inDataStream.close();
}
}
Reading Data Back in Right
Order The order of write and read operations must match in
order to read the stored primitive data back correctly.
Reading & Writing Textfile
 Instead of storing primitive data values
as binary data in a file, we can convert
and store them as a string data.
This allows us to view the file content using
any text editor
 To write data as a string to text file, use
a FileWriter and PrintWriter object
 To read data from textfile, use
FileReader and BufferedReader classes
From Java 5.0 (SDK 1.5), we can also use
the Scanner class for reading textfiles
Sample Writing to Textfile
import java.io.*;
class Ch12TestPrintWriter {
public static void main (String[] args) throws IOException {
//set up file and stream
File outFile = new File("sample3.data");
FileWriter outFileStream
= new FileWriter(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
//write values of primitive data types to the stream
outStream.println(987654321);
outStream.println("Hello, world.");
outStream.println(true);
//output done, so close the stream
outStream.close();
}
}
Sample Reading from
Textfileimport java.io.*;
class Ch12TestBufferedReader {
public static void main (String[] args) throws IOException {
//set up file and stream
File inFile = new File("sample3.data");
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 Reading Textfile
using Scanner
import java.io.*;
class Ch12TestScanner {
public static void main (String[] args) throws IOException {
//open the Scanner
File inFile = new File("sample3.data");
Scanner scanner = new Scanner(inFile);
//get integer
int i = scanner.nextInt();
//similar process for other data types
scanner.close();
}
}
try{
// read line one by one till all line is read.
Scanner scanner = new Scanner(inFile);
while (scanner.hasNextLine()) { //check if there are more line
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Sample Reading Textfile using Scanner
Code fragments shows how to read the whole contents of a file
Use hasNextLine() & nextLine() methods

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Type conversion
Type  conversionType  conversion
Type conversion
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Introduction To Autumata Theory
 Introduction To Autumata Theory Introduction To Autumata Theory
Introduction To Autumata Theory
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Looping statement
Looping statementLooping statement
Looping statement
 
Files in c++
Files in c++Files in c++
Files in c++
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
3 Level Architecture
3 Level Architecture3 Level Architecture
3 Level Architecture
 
DATABASE MANAGEMENT SYSTEM PRACTICAL LAB ASSIGNMENT 1
DATABASE MANAGEMENT SYSTEM PRACTICAL LAB ASSIGNMENT 1DATABASE MANAGEMENT SYSTEM PRACTICAL LAB ASSIGNMENT 1
DATABASE MANAGEMENT SYSTEM PRACTICAL LAB ASSIGNMENT 1
 
Data file handling
Data file handlingData file handling
Data file handling
 
C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbms
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
File Pointers
File PointersFile Pointers
File Pointers
 

Similar a File Input & Output

Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3sotlsoc
 
Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1sotlsoc
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentationAzeemaj101
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSVenugopalavarma Raja
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & MultiplexingMelkamuEndale1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxAssadLeo1
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
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
 

Similar a File Input & Output (20)

Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
File Organization
File OrganizationFile Organization
File Organization
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
Java file
Java fileJava file
Java file
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & Multiplexing
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Java File I/O
Java File I/OJava File I/O
Java File I/O
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
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
 

Más de PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And ExpressionPRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and JavaPRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 

Más de PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Último

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
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
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
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
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
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
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Último (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
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
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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.
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
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
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
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
 

File Input & Output

  • 1. File Input and Output
  • 2. Objectives  After you have read and studied this chapter, you should be able to  Use File object to get info about a file  Include a JFileChooser object in your program to let the user specify a file.  Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream.  Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream.  Write text data to a file and read them back from the file, using FileWriter,PrintWriter and FileReader,BufferedReader  Read a text file using Scanner
  • 3. File  File is regarded as a collection of bytes  When a file is read, computer delivers some of those bytes to the program.  When a file is written, computer accepts some bytes from the program and saves them in part of the file.  Computer makes no distinction between eg. image files and text files. Its all bytes to the hardware. What those bytes are used for is up to the software.
  • 4. Types of File  All information in any file is kept in binary form.
  • 5. Types of File  File can be categorized as text (ASCII) file or binary file.  A text file is a file that contains bytes that represent:  characters 'A' through 'Z'  characters 'a' through 'z'  characters '0' through '9'  the space character  punctuation and symbols like . , : ; " + - $ (and others)  a few control characters that represent end of lines, tabs and some other things. using ASCII Codes  A binary file is a file that contains bytes that represent others (eg. numbers, image, audio, formatted text etc)
  • 6. The File Class The File class (from java.io). can be used to obtain info about file  To do this, we must first create a File object  A File object can represent a file or a directory File inFile = new File(“sample.dat”); File inFile = new File (“C:/SamplePrograms/test.dat”); Creates File object for the file sample.dat in the current directory. Creates File object for the file sample.dat in the current directory. Creates File object for the file test.dat in the directory C:SamplePrograms using the generic file separator / and providing the full pathname. Creates File object for the file test.dat in the directory C:SamplePrograms using the generic file separator / and providing the full pathname.
  • 7. Some File Methods if ( inFile.exists( ) ) { if ( inFile.isFile() ) { File directory = new File("C:/JavaPrograms/Ch12"); String filename[] = directory.list(); for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]); } To see if inFile is associated to a real file correctly. To see if inFile is associated to a real file correctly. To see if inFile is associated to a file. If false, it is a directory. Also, can test directly if it is a directory. To see if inFile is associated to a file. If false, it is a directory. Also, can test directly if it is a directory. List the name of all files in the directory C:JavaProjectsCh12 List the name of all files in the directory C:JavaProjectsCh12 if ( inFile.isDirectory() ) {
  • 8. Some File Methods if ( inFile.length( ) ) { if ( inFile.canRead() ) { To see the size of the file in bytes represented by inFile To see the size of the file in bytes represented by inFile To see if inFile is associated to a file that exist & can be read To see if inFile is associated to a file that exist & can be read if ( inFile.canWrite() ) { To see if inFile is associated to a file that exist & can be written To see if inFile is associated to a file that exist & can be written if ( inFile.getName() ) { To get the name of the file represented by inFile To get the name of the file represented by inFile
  • 9. The JFileChooser Class  A javax.swing.JFileChooser object allows the user to select a file. JFileChooser chooser = new JFileChooser( ); chooser.showOpenDialog(null); JFileChooser chooser = new JFileChooser("D:/JavaPrograms/Ch12"); chooser.showOpenDialog(null); To start the listing from a specific directory:
  • 11. Getting Info from JFileChooser int status = chooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { JOptionPane.showMessageDialog(null, "Open is clicked"); } else { //== JFileChooser.CANCEL_OPTION JOptionPane.showMessageDialog(null, "Cancel is clicked"); } File selectedFile = chooser.getSelectedFile(); File currentDirectory = chooser.getCurrentDirectory();
  • 12. I/O Streams  To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file.  A stream is a sequence of data items, usually 8-bit bytes.  Java has two types of streams: an input stream and an output stream.  An input stream has a source form which the data items come, and an output stream has a destination to which
  • 14. I/O Streams  IO streams are either character-oriented or byte- oriented.  Character-oriented IO has special features for handling character data (text files).  Byte-oriented IO is for all types of data (binary files) IO class Hierarchy in java.io package
  • 15. Streams for Byte –level Binary File I/O  FileOutputStream and FileInputStream are two stream objects that facilitate file access.  FileOutputStream allows us to output a sequence of bytes; values of data type byte.  FileInputStream allows us to read in an array of bytes.
  • 16. Sample: Byte-level Binary File Output//set up file and stream File outFile = new File("sample1.data"); 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();
  • 17. Sample: Byte-level Binary File Input//set up file and stream File inFile = new File("sample1.data"); 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();
  • 18. Streams for Data-Level Binary File I/O  FileOutputStream and DataOutputStream are used to output primitive data values  FileInputStream and DataInputStream are used to input primitive data values  To read the data back correctly, we must know the order of the data stored and their data types
  • 19. Setting up DataOutputStream A standard sequence to set up a DataOutputStream object:
  • 20. 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(); } }
  • 21. Setting up DataInputStream A standard sequence to set up a DataInputStream object:
  • 22. 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(); } }
  • 23. Reading Data Back in Right Order The order of write and read operations must match in order to read the stored primitive data back correctly.
  • 24. Reading & Writing Textfile  Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. This allows us to view the file content using any text editor  To write data as a string to text file, use a FileWriter and PrintWriter object  To read data from textfile, use FileReader and BufferedReader classes From Java 5.0 (SDK 1.5), we can also use the Scanner class for reading textfiles
  • 25. Sample Writing to Textfile import java.io.*; class Ch12TestPrintWriter { public static void main (String[] args) throws IOException { //set up file and stream File outFile = new File("sample3.data"); FileWriter outFileStream = new FileWriter(outFile); PrintWriter outStream = new PrintWriter(outFileStream); //write values of primitive data types to the stream outStream.println(987654321); outStream.println("Hello, world."); outStream.println(true); //output done, so close the stream outStream.close(); } }
  • 26. Sample Reading from Textfileimport java.io.*; class Ch12TestBufferedReader { public static void main (String[] args) throws IOException { //set up file and stream File inFile = new File("sample3.data"); 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(); } }
  • 27. Sample Reading Textfile using Scanner import java.io.*; class Ch12TestScanner { public static void main (String[] args) throws IOException { //open the Scanner File inFile = new File("sample3.data"); Scanner scanner = new Scanner(inFile); //get integer int i = scanner.nextInt(); //similar process for other data types scanner.close(); } }
  • 28. try{ // read line one by one till all line is read. Scanner scanner = new Scanner(inFile); while (scanner.hasNextLine()) { //check if there are more line String line = scanner.nextLine(); System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } Sample Reading Textfile using Scanner Code fragments shows how to read the whole contents of a file Use hasNextLine() & nextLine() methods

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. 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));
  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 FileoutFile = new File(&amp;quot;sample1.data&amp;quot;); FileOutputStreamoutStream = 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 FileinFile= 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 &amp;lt; fileSize; i++) { outputBox.printLine(byteArray[i]); } //input done, so close the stream inStream.close(); } }