SlideShare a Scribd company logo
Topic 5: Input and Output
Reading: Chapter 12
Advanced Programming Techniques
Objectives and Outline
• Objectives:
– Overall view i/o in java
– Reading and writing local files
• Outline
– Introduction and overview
– Reading and writing local files
• Connecting to files
• Reading and writing characters
• Reading and writing objects
– File management
Introduction and Overview
• When talking about IO, we need to consider files
– At different locations:
• blocks of main memory
• local file system
• over the net
– In different formats:
• text or binary
• zipped or not zipped
– With different access modes:
• plain sequential,
• buffered,
• pushback,
• Random
Introduction and Overview
• Java streams
– Input streams:
• Objects from where we read input sequences
– Output stream:
• Objects where we write output sequences
• Java has stream classes allow us to deal with all possible combinations of
location, format, and access mode.
• In particular, Java streams provide an abstraction of files at different
locations
– Local files and files from internet can be handled the same way.
– We discuss only local files in this lecture.
• In the next few slides, we give some of the stream classes
Introduction and Overview
All classes for reading from character streams inherit from
abstact class Reader
Reader has one abstract method read, which returns the next
unicode character or –1 (EOF)
Reader
LineNumber
Reader
Pushback
Reader
InputStream
Reader
CharArray
Reader
Filter
Reader
Buffered
Reader
String
Reader
Piped
Reader
File
Reader
Introduction and Overview
All classes for writing character streams inherit from abstact
class Writer
Writer has one abstract method write(int b), which writes
a unicode charater to an output
Writer
Print
Writer
File
Writer
Buffered
Writer
OutputStream
Writer
Piped
Writer
Filter
Writer
CharArray
Writer
String
Writer
Introduction and Overview
All classes for reading from byte streams inherit from abstact
class InputStream
InputStream has one abstract method read, which returns
the next byte character or –1 (EOF)
InputStream
Pushback
InputStream
LineNumber
InputStream
Data
InputStream
Buffered
InputStream
File
InputStream
ByteArray
InputStream
Filter
InputStream
Sequence
InputStream
StringBuffer
InputStream
Object
InputStream
Piped
InputStream
. . . .
Introduction and Overview
All classes for writing to byte streams inherit from abstact class
OutputStream
OutputStream has one abstract method write(int b),
which writes one byte to an output
OutputStream
Checked
OutputStream
PrintStream
Data
OutputStream
Buffered
OutputStream
ByteArray
OutputStream
Filter
OutputStream
Object
OutputStream
Piped
OutputStream
. . . .
File
OutputStream
Reading and Writing local files
• Plan
• Connecting to files: open files
• Reading and writing characters
– Parsing
• Reading and writing objects
Connecting to Files
• Open a file for writing bytes
– FileOutputStream out = new FileOutputStream(“employee.dat”);
– FileOutputStream has method for writing bytes: out.write(int b);
– Seldom write individual bytes
– write method used by higher level streams
• Open a file for reading bytes
– FileInputStream in = new FileInputStream(“employee.dat”);
– FileInputStream has method for reading bytes
in.read();
– Seldom read individual bytes
– read method used by higher level streams
Writing Characters
• An OutputStreamWriter is a bridge from character streams to byte
streams
– Has method for writing character: void write(int c)
• Nesting OutputStreamWriter with FileOutputStream allows us
to write individual characters to files
– OutputStreamWriter out = new OutputStreamWriter (new
FileOutputStream(“employee.dat”) );
– If out.write(‘a’), out.flush() then ‘a’ goes to the file (“employee.dat”).
• Two classes in action here
– One converts ‘a’ into bytes
– One write bytes to file
Writing Characters
• The combination of OutputStreamWriter and
FileOutputStream is commonly used.
• A convenience class FileWriter is hence introduced
FileWriter f = new FileWriter(“employee.dat”);
is equivalent to
OutputStreamWriter f = new OutputStreamWriter( new
FileOutputStream(“employee.dat”));
Writing Charaters
• Seldom write characters one by one
– Usually write strings. How to write Strings?
• PrintWriter prints formatted representations of objects to a text-output
stream
– Has methods print and println.
• Example
– PrintWriter out = new PrintWriter( new
FileWriter(“employee.dat”));
– If out.println(“this is a test”),
• then the string “this is a test” goes to file “employee.dat”
– Three classes in action here
• PrintWriter breaks the string into characters
• OutputStreamWriter converts characters into bytes
• FileOutputStream writes bytes to file
WriteTextTest.java
Reading Characters
• For writing we have
– FileOutputStream,
OutputStreamWriter, FileWriter,
PrintWriter
• For reading we have
– FileInputStream,
InputStreamReader, FileReader,
BufferedReader
• BufferedReader has method readLine for reading one line
ReadTextTest.java
Read and Write Standard IO
• System.out predefined PrintStream, stands for screen.
Print to screen:
l System.out.print(); System.out.println();
• System.in predefined InputStream, stands for keyboard.
Nest System.in with BufferedReader
Use method readLine
• Example: Echo.java
Parsing
Reading a text file / Parsing input
s=readLine() gives you a long string.
Need to break the string into individual strings and
convert them into proper type.
To do this, use the StringTokenizer class in
java.util.
Create a StringTokenizer object for the
delimiter “|”
StringTokenizer t = new StringTokenizer(s, “|”);
Parsing
Reading a text file / Parsing input
Use the nextToken method to extract the next piece from
string.
t.nextToken() --- name.
t.nextToken() --- salary as string. Need Double.parseDouble
t.nextToken() --- year as string. Need Integer.parseInt
t.nextToken() --- month as string. Need Integer.parseInt
t.nextToken() --- day as string. Need Integer.parseInt
Here we know that there are 5 tokens on each line.
In general, call t.hasMoreTokens before each
t.nextToken
Use StreamTokenizer to parse a file
DataFileTest.java
Reading and Writing Objects
• When useful
– Need to save some information and retrieve it
later.
– Saved information does not have to be human
readable.
• Why bother (since we can write and read text
files)
– Much easier than writing and reading text files
Writing Objects
To save an object, open an ObjectOutputStream
ObjectOutputStream out =
new ObjectOutputStream (
new FileOutputStream(“employee.dat”));
Simply use writeObject method to save an object
Employee harry = new Employee("Harry Hacker", 35000,
new Day(1989,10,1));
Manager carl = new Manager("Carl Cracker", 75000,
new Day(1987,12,15));
out.writeObject(harry);
out.writeObject(carl);
Reading Objects
To get back an object, open an ObjectInputStream
ObjectInputStream in = new ObjectInputStream (
new FileInputStream(“employee.dat”));
Use readObject method to retrieve objects in the same order in
which they were written
Employee e1 = (Employee) in.readObject();
Employee e2 = (Employee) in.readObject();
Cast necessary because readObject returns an object of class
Object.
Serializable Interface
• For object writing/reading to work, the class
must implement the serializable interface
– Class Employee implements
Serializable(){…}
• Since Arrays, one can write/read an array of
any objects in one sentence
– Employee[] staff; …
– out.writeObject( staff );
– (Employee[])in.readObject();
ObjectFileTest.java
File Management
• Use java.io.File
• Creating a new directory:
– Create a File object
File tempDir = new File( “temp”);
– Create directory
tempDir.mkdir();
• Creating a new file
– Create a File object:
File foo = new File(“dirName”+File.separator +
“data.txt”);
File foo = new File(“dirName”, “data.txt”);
– Create file
File Management
• Inspecting contents of a directory
someDir.list() returns an array of file names
under the directory
• Deleting files and directories
someDir.delete();
someFile.delete();
FindDirectories.java

More Related Content

What's hot

IO In Java
IO In JavaIO In Java
IO In Java
parag
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
Input output streams
Input output streamsInput output streams
Input output streams
Parthipan Parthi
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
santosh mishra
 
Java stereams
Java stereamsJava stereams
Java stereams
Jernej Virag
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
Java I/O
Java I/OJava I/O
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Manav Prasad
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Tien Nguyen
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
Deepak Hagadur Bheemaraju
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
Azeemaj101
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 

What's hot (19)

IO In Java
IO In JavaIO In Java
IO In Java
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java IO
Java IOJava IO
Java IO
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
14 file handling
14 file handling14 file handling
14 file handling
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Java stereams
Java stereamsJava stereams
Java stereams
 
Java stream
Java streamJava stream
Java stream
 
Java I/O
Java I/OJava I/O
Java I/O
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
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
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 

Viewers also liked

FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
Alicia Mohart
 
A pedagogia da repetência
A pedagogia da repetênciaA pedagogia da repetência
A pedagogia da repetência
Renata Rabelo
 
Cyber912 student challenge_two_pager_sponsors
Cyber912 student challenge_two_pager_sponsorsCyber912 student challenge_two_pager_sponsors
Cyber912 student challenge_two_pager_sponsors
atlanticcouncil
 
Body Transformation Final
Body Transformation FinalBody Transformation Final
Body Transformation Final
Jourdan Baldwin
 
Evaulation 2
Evaulation 2Evaulation 2
Evaulation 2
angeliquebates
 
Cembre 2A30 Crimp Lugs 1520sqmm 11-33kV
Cembre 2A30 Crimp Lugs 1520sqmm 11-33kVCembre 2A30 Crimp Lugs 1520sqmm 11-33kV
Cembre 2A30 Crimp Lugs 1520sqmm 11-33kV
Thorne & Derrick International
 
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
Alicia Mohart
 
เทคโนโลยีกาารสอน
เทคโนโลยีกาารสอนเทคโนโลยีกาารสอน
เทคโนโลยีกาารสอน08744478333
 
CENCIR Poster
CENCIR PosterCENCIR Poster
CENCIR Poster
Qingtian Chen
 
Mohart Sweet Treats-Action Pack Bar-Alicia Mohart
Mohart Sweet Treats-Action Pack Bar-Alicia MohartMohart Sweet Treats-Action Pack Bar-Alicia Mohart
Mohart Sweet Treats-Action Pack Bar-Alicia Mohart
Alicia Mohart
 
Question 2
Question 2Question 2
Writing letters to patients and copying GP in
Writing letters to patients and copying GP inWriting letters to patients and copying GP in
Writing letters to patients and copying GP in
NHS Improving Quality
 
Avances tecnologicos 1°f (1)
Avances tecnologicos 1°f (1)Avances tecnologicos 1°f (1)
Avances tecnologicos 1°f (1)
MauricioSaldivar
 
Tunisia: The Last Arab Spring Country
Tunisia: The Last Arab Spring CountryTunisia: The Last Arab Spring Country
Tunisia: The Last Arab Spring Country
atlanticcouncil
 
Securing Ukraine's Energy Sector
Securing Ukraine's Energy SectorSecuring Ukraine's Energy Sector
Securing Ukraine's Energy Sector
atlanticcouncil
 

Viewers also liked (15)

FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
 
A pedagogia da repetência
A pedagogia da repetênciaA pedagogia da repetência
A pedagogia da repetência
 
Cyber912 student challenge_two_pager_sponsors
Cyber912 student challenge_two_pager_sponsorsCyber912 student challenge_two_pager_sponsors
Cyber912 student challenge_two_pager_sponsors
 
Body Transformation Final
Body Transformation FinalBody Transformation Final
Body Transformation Final
 
Evaulation 2
Evaulation 2Evaulation 2
Evaulation 2
 
Cembre 2A30 Crimp Lugs 1520sqmm 11-33kV
Cembre 2A30 Crimp Lugs 1520sqmm 11-33kVCembre 2A30 Crimp Lugs 1520sqmm 11-33kV
Cembre 2A30 Crimp Lugs 1520sqmm 11-33kV
 
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
FinalandcorrectTable of Contents-DaVeeVang-AliciaMohart (1)
 
เทคโนโลยีกาารสอน
เทคโนโลยีกาารสอนเทคโนโลยีกาารสอน
เทคโนโลยีกาารสอน
 
CENCIR Poster
CENCIR PosterCENCIR Poster
CENCIR Poster
 
Mohart Sweet Treats-Action Pack Bar-Alicia Mohart
Mohart Sweet Treats-Action Pack Bar-Alicia MohartMohart Sweet Treats-Action Pack Bar-Alicia Mohart
Mohart Sweet Treats-Action Pack Bar-Alicia Mohart
 
Question 2
Question 2Question 2
Question 2
 
Writing letters to patients and copying GP in
Writing letters to patients and copying GP inWriting letters to patients and copying GP in
Writing letters to patients and copying GP in
 
Avances tecnologicos 1°f (1)
Avances tecnologicos 1°f (1)Avances tecnologicos 1°f (1)
Avances tecnologicos 1°f (1)
 
Tunisia: The Last Arab Spring Country
Tunisia: The Last Arab Spring CountryTunisia: The Last Arab Spring Country
Tunisia: The Last Arab Spring Country
 
Securing Ukraine's Energy Sector
Securing Ukraine's Energy SectorSecuring Ukraine's Energy Sector
Securing Ukraine's Energy Sector
 

Similar to 05io

ch09.ppt
ch09.pptch09.ppt
ch09.ppt
NiharikaDubey17
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
PawanMM
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
Java
JavaJava
Chapter 2.1 : Data Stream
Chapter 2.1 : Data StreamChapter 2.1 : Data Stream
Chapter 2.1 : Data Stream
Ministry of Higher Education
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
hemanth248901
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
Berk Soysal
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
botin17097
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
Srinivas Narasegouda
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
Blue Elephant Consulting
 
Data file handling
Data file handlingData file handling
Data file handling
Saurabh Patel
 
File handling & basic operation on file in python
File handling & basic operation on file in pythonFile handling & basic operation on file in python
File handling & basic operation on file in python
ishantjaiswal2004
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
qover
 

Similar to 05io (20)

ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
Java
JavaJava
Java
 
Chapter 2.1 : Data Stream
Chapter 2.1 : Data StreamChapter 2.1 : Data Stream
Chapter 2.1 : Data Stream
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
Python file handling
Python file handlingPython file handling
Python file handling
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
 
Data file handling
Data file handlingData file handling
Data file handling
 
File handling & basic operation on file in python
File handling & basic operation on file in pythonFile handling & basic operation on file in python
File handling & basic operation on file in python
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
 

More from Waheed Warraich

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
Waheed Warraich
 
java networking
 java networking java networking
java networking
Waheed Warraich
 
java threads
java threadsjava threads
java threads
Waheed Warraich
 
java applets
java appletsjava applets
java applets
Waheed Warraich
 
java swing
java swingjava swing
java swing
Waheed Warraich
 
09events
09events09events
09events
Waheed Warraich
 
08graphics
08graphics08graphics
08graphics
Waheed Warraich
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
Waheed Warraich
 
04inherit
04inherit04inherit
04inherit
Waheed Warraich
 
03class
03class03class
02basics
02basics02basics
02basics
Waheed Warraich
 
01intro
01intro01intro

More from Waheed Warraich (12)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
java networking
 java networking java networking
java networking
 
java threads
java threadsjava threads
java threads
 
java applets
java appletsjava applets
java applets
 
java swing
java swingjava swing
java swing
 
09events
09events09events
09events
 
08graphics
08graphics08graphics
08graphics
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
04inherit
04inherit04inherit
04inherit
 
03class
03class03class
03class
 
02basics
02basics02basics
02basics
 
01intro
01intro01intro
01intro
 

Recently uploaded

A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 

Recently uploaded (20)

A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 

05io

  • 1. Topic 5: Input and Output Reading: Chapter 12 Advanced Programming Techniques
  • 2. Objectives and Outline • Objectives: – Overall view i/o in java – Reading and writing local files • Outline – Introduction and overview – Reading and writing local files • Connecting to files • Reading and writing characters • Reading and writing objects – File management
  • 3. Introduction and Overview • When talking about IO, we need to consider files – At different locations: • blocks of main memory • local file system • over the net – In different formats: • text or binary • zipped or not zipped – With different access modes: • plain sequential, • buffered, • pushback, • Random
  • 4. Introduction and Overview • Java streams – Input streams: • Objects from where we read input sequences – Output stream: • Objects where we write output sequences • Java has stream classes allow us to deal with all possible combinations of location, format, and access mode. • In particular, Java streams provide an abstraction of files at different locations – Local files and files from internet can be handled the same way. – We discuss only local files in this lecture. • In the next few slides, we give some of the stream classes
  • 5. Introduction and Overview All classes for reading from character streams inherit from abstact class Reader Reader has one abstract method read, which returns the next unicode character or –1 (EOF) Reader LineNumber Reader Pushback Reader InputStream Reader CharArray Reader Filter Reader Buffered Reader String Reader Piped Reader File Reader
  • 6. Introduction and Overview All classes for writing character streams inherit from abstact class Writer Writer has one abstract method write(int b), which writes a unicode charater to an output Writer Print Writer File Writer Buffered Writer OutputStream Writer Piped Writer Filter Writer CharArray Writer String Writer
  • 7. Introduction and Overview All classes for reading from byte streams inherit from abstact class InputStream InputStream has one abstract method read, which returns the next byte character or –1 (EOF) InputStream Pushback InputStream LineNumber InputStream Data InputStream Buffered InputStream File InputStream ByteArray InputStream Filter InputStream Sequence InputStream StringBuffer InputStream Object InputStream Piped InputStream . . . .
  • 8. Introduction and Overview All classes for writing to byte streams inherit from abstact class OutputStream OutputStream has one abstract method write(int b), which writes one byte to an output OutputStream Checked OutputStream PrintStream Data OutputStream Buffered OutputStream ByteArray OutputStream Filter OutputStream Object OutputStream Piped OutputStream . . . . File OutputStream
  • 9. Reading and Writing local files • Plan • Connecting to files: open files • Reading and writing characters – Parsing • Reading and writing objects
  • 10. Connecting to Files • Open a file for writing bytes – FileOutputStream out = new FileOutputStream(“employee.dat”); – FileOutputStream has method for writing bytes: out.write(int b); – Seldom write individual bytes – write method used by higher level streams • Open a file for reading bytes – FileInputStream in = new FileInputStream(“employee.dat”); – FileInputStream has method for reading bytes in.read(); – Seldom read individual bytes – read method used by higher level streams
  • 11. Writing Characters • An OutputStreamWriter is a bridge from character streams to byte streams – Has method for writing character: void write(int c) • Nesting OutputStreamWriter with FileOutputStream allows us to write individual characters to files – OutputStreamWriter out = new OutputStreamWriter (new FileOutputStream(“employee.dat”) ); – If out.write(‘a’), out.flush() then ‘a’ goes to the file (“employee.dat”). • Two classes in action here – One converts ‘a’ into bytes – One write bytes to file
  • 12. Writing Characters • The combination of OutputStreamWriter and FileOutputStream is commonly used. • A convenience class FileWriter is hence introduced FileWriter f = new FileWriter(“employee.dat”); is equivalent to OutputStreamWriter f = new OutputStreamWriter( new FileOutputStream(“employee.dat”));
  • 13. Writing Charaters • Seldom write characters one by one – Usually write strings. How to write Strings? • PrintWriter prints formatted representations of objects to a text-output stream – Has methods print and println. • Example – PrintWriter out = new PrintWriter( new FileWriter(“employee.dat”)); – If out.println(“this is a test”), • then the string “this is a test” goes to file “employee.dat” – Three classes in action here • PrintWriter breaks the string into characters • OutputStreamWriter converts characters into bytes • FileOutputStream writes bytes to file WriteTextTest.java
  • 14. Reading Characters • For writing we have – FileOutputStream, OutputStreamWriter, FileWriter, PrintWriter • For reading we have – FileInputStream, InputStreamReader, FileReader, BufferedReader • BufferedReader has method readLine for reading one line ReadTextTest.java
  • 15. Read and Write Standard IO • System.out predefined PrintStream, stands for screen. Print to screen: l System.out.print(); System.out.println(); • System.in predefined InputStream, stands for keyboard. Nest System.in with BufferedReader Use method readLine • Example: Echo.java
  • 16. Parsing Reading a text file / Parsing input s=readLine() gives you a long string. Need to break the string into individual strings and convert them into proper type. To do this, use the StringTokenizer class in java.util. Create a StringTokenizer object for the delimiter “|” StringTokenizer t = new StringTokenizer(s, “|”);
  • 17. Parsing Reading a text file / Parsing input Use the nextToken method to extract the next piece from string. t.nextToken() --- name. t.nextToken() --- salary as string. Need Double.parseDouble t.nextToken() --- year as string. Need Integer.parseInt t.nextToken() --- month as string. Need Integer.parseInt t.nextToken() --- day as string. Need Integer.parseInt Here we know that there are 5 tokens on each line. In general, call t.hasMoreTokens before each t.nextToken Use StreamTokenizer to parse a file DataFileTest.java
  • 18. Reading and Writing Objects • When useful – Need to save some information and retrieve it later. – Saved information does not have to be human readable. • Why bother (since we can write and read text files) – Much easier than writing and reading text files
  • 19. Writing Objects To save an object, open an ObjectOutputStream ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream(“employee.dat”)); Simply use writeObject method to save an object Employee harry = new Employee("Harry Hacker", 35000, new Day(1989,10,1)); Manager carl = new Manager("Carl Cracker", 75000, new Day(1987,12,15)); out.writeObject(harry); out.writeObject(carl);
  • 20. Reading Objects To get back an object, open an ObjectInputStream ObjectInputStream in = new ObjectInputStream ( new FileInputStream(“employee.dat”)); Use readObject method to retrieve objects in the same order in which they were written Employee e1 = (Employee) in.readObject(); Employee e2 = (Employee) in.readObject(); Cast necessary because readObject returns an object of class Object.
  • 21. Serializable Interface • For object writing/reading to work, the class must implement the serializable interface – Class Employee implements Serializable(){…} • Since Arrays, one can write/read an array of any objects in one sentence – Employee[] staff; … – out.writeObject( staff ); – (Employee[])in.readObject(); ObjectFileTest.java
  • 22. File Management • Use java.io.File • Creating a new directory: – Create a File object File tempDir = new File( “temp”); – Create directory tempDir.mkdir(); • Creating a new file – Create a File object: File foo = new File(“dirName”+File.separator + “data.txt”); File foo = new File(“dirName”, “data.txt”); – Create file
  • 23. File Management • Inspecting contents of a directory someDir.list() returns an array of file names under the directory • Deleting files and directories someDir.delete(); someFile.delete(); FindDirectories.java