SlideShare a Scribd company logo
7-Jun-21
Simple Java I/O
Part I
General Principles
2
Prologue
“They say you can hold seven plus or minus two pieces of
information in your mind. I can’t remember how to open
files in Java. I’ve written chapters on it. I’ve done it a
bunch of times, but it’s too many steps. And when I
actually analyze it, I realize these are just silly design
decisions that they made. Even if they insisted on using
the Decorator pattern in java.io, they should have had
a convenience constructor for opening files simply.
Because we open files all the time, but nobody can
remember how. It is too much information to hold in
your mind.”
—Bruce Eckel, http://www.artima.com/intv/aboutme2.html
3
Streams
 All modern I/O is stream-based
 A stream is a connection to a source of data or to a
destination for data (sometimes both)
 An input stream may be associated with the keyboard
 An input stream or an output stream may be
associated with a file
 Different streams have different characteristics:
 A file has a definite length, and therefore an end
 Keyboard input has no specific end
4
How to do I/O
import java.io.*;
 Open the stream
 Use the stream (read, write, or both)
 Close the stream
5
Why Java I/O is hard
 Java I/O is very powerful, with an overwhelming
number of options
 Any given kind of I/O is not particularly difficult
 The trick is to find your way through the maze of
possibilities
open
use
close
6
Opening a stream
 There is data external to your program that you want to
get, or you want to put data somewhere outside your
program
 When you open a stream, you are making a connection
to that external place
 Once the connection is made, you forget about the
external place and just use the stream
open
use
close
7
Example of opening a stream
 A FileReader is a used to connect to a file that will be
used for input:
FileReader fileReader =
new FileReader(fileName);
 The fileName specifies where the (external) file is to be
found
 You never use fileName again; instead, you use
fileReader
open
use
close
8
Using a stream
 Some streams can be used only for input, others only for
output, still others for both
 Using a stream means doing input from it or output to it
 But it’s not usually that simple--you need to manipulate
the data in some way as it comes in or goes out
open
use
close
9
Example of using a stream
int charAsInt;
charAsInt = fileReader.read( );
 The fileReader.read() method reads one character and
returns it as an integer, or -1 if there are no more
characters to read
 The meaning of the integer depends on the file encoding
(ASCII, Unicode, other)
 You can cast from int to char:
char ch = (char)fileReader.read( );
 FileReaderExample1.java
open
use
close
10
Manipulating the input data
 Reading characters as integers isn’t usually what you
want to do
 A BufferedReader will convert integers to characters;
it can also read whole lines
 The constructor for BufferedReader takes a
FileReader parameter:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
open
use
close
11
Reading lines
String s;
s = bufferedReader.readLine( );
 A BufferedReader will return null if there is
nothing more to read
 FileReaderExample2.java
open
use
close
12
Closing
 A stream is an expensive resource
 There is a limit on the number of streams that you can
have open at one time
 You should not have more than one stream open on
the same file
 You must close a stream before you can open it again
 Always close your streams!
 Java will normally close your streams for you when
your program ends, but it isn’t good style to depend on
this
open
use
close
7-Jun-21
Simple Java I/O
Part II
LineReader and LineWriter
14
Text files
 Text (.txt) files are the simplest kind of files
 Text files can be used by many different programs
 Formatted text files (such as .doc files) also contain
binary formatting information
 Only programs that “know the secret code” can
make sense of formatted text files
 Compilers, in general, work only with text
15
My LineReader class
class LineReader {
BufferedReader bufferedReader;
LineReader(String fileName) {...}
String readLine( ) {...}
void close( ) {...}
}
16
Basics of the LineReader constructor
 Create a FileReader for the named file:
FileReader fileReader =
new FileReader(fileName);
 Use it as input to a BufferedReader:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
 Use the BufferedReader; but first, we need to
catch possible Exceptions
17
The full LineReader constructor
LineReader(String fileName) {
FileReader fileReader = null;
try { fileReader = new FileReader(fileName); }
catch (FileNotFoundException e) {
System.err.println
("LineReader can’t find input file: " + fileName);
e.printStackTrace( );
}
bufferedReader = new BufferedReader(fileReader);
}
18
readLine
String readLine( ) {
try {
return bufferedReader.readLine( );
}
catch(IOException e) {
e.printStackTrace( );
}
return null;
}
19
close
void close() {
try {
bufferedReader.close( );
}
catch(IOException e) { }
}
20
How did I figure that out?
 I wanted to read lines from a file
 I thought there might be a suitable readSomething method, so
I went to the API Index
 Note: Capital letters are all alphabetized before lowercase in the Index
 I found a readLine method in several classes; the most
promising was the BufferedReader class
 The constructor for BufferedReader takes a Reader as an
argument
 Reader is an abstract class, but it has several implementations,
including InputStreamReader
 FileReader is a subclass of InputStreamReader
 There is a constructor for FileReader that takes as its
argument a (String) file name
21
The LineWriter class
class LineWriter {
PrintWriter printWriter;
LineWriter(String fileName) {...}
void writeLine(String line) {...}
void close( ) {...}
}
22
The constructor for LineWriter
LineWriter(String fileName) {
try {
printWriter =
new PrintWriter(
new FileOutputStream(fileName), true);
}
catch(Exception e) {
System.err.println("LineWriter can’t " +
"use output file: " + fileName);
}
}
23
Flushing the buffer
 When you put information into a buffered output
stream, it goes into a buffer
 The buffer may or may not be written out right away
 If your program crashes, you may not know how far
it got before it crashed
 Flushing the buffer forces the information to be
written out
24
PrintWriter
 Buffers are automatically flushed when the program
ends normally
 Usually it is your responsibility to flush buffers if
the program does not end normally
 PrintWriter can do the flushing for you
public PrintWriter(OutputStream out,
boolean autoFlush)
25
writeLine
void writeLine(String line) {
printWriter.println(line);
}
26
close
void close( ) {
printWriter.flush( );
try {
printWriter.close( );
}
catch(Exception e) { }
}

More Related Content

What's hot

Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
CIB Egypt
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
Input output streams
Input output streamsInput output streams
Input output streams
Parthipan Parthi
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
File handling
File handlingFile handling
File handling
Amber Wajid
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
File handling in c++
File handling in c++File handling in c++
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
C# File IO Operations
C# File IO OperationsC# File IO Operations
C# File IO Operations
Prem Kumar Badri
 
data file handling
data file handlingdata file handling
data file handling
krishna partiwala
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
File Handling in C++
File Handling in C++File Handling in C++
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
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
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
keeeerty
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 

What's hot (20)

Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
14 file handling
14 file handling14 file handling
14 file handling
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
 
File handling
File handlingFile handling
File handling
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Java IO
Java IOJava IO
Java IO
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
C# File IO Operations
C# File IO OperationsC# File IO Operations
C# File IO Operations
 
data file handling
data file handlingdata file handling
data file handling
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
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
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 

Similar to Javaio

Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
Jstreams
JstreamsJstreams
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
NiharikaDubey17
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
Java file
Java fileJava file
Java file
sonnetdp
 
Java I/O
Java I/OJava I/O
Java I/O
DeeptiJava
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
WondimuBantihun1
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
15. text files
15. text files15. text files
15. text files
Konstantin Potemichev
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
ChereLemma2
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
study material
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 

Similar to Javaio (20)

Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Jstreams
JstreamsJstreams
Jstreams
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
Python-files
Python-filesPython-files
Python-files
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
File management in C++
File management in C++File management in C++
File management in C++
 
Java file
Java fileJava file
Java file
 
Java I/O
Java I/OJava I/O
Java I/O
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
Data file handling
Data file handlingData file handling
Data file handling
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
15. text files
15. text files15. text files
15. text files
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 

More from Jaya Jeswani

Assignment java workshop
Assignment java workshopAssignment java workshop
Assignment java workshop
Jaya Jeswani
 
Assignment java workshop
Assignment java workshopAssignment java workshop
Assignment java workshop
Jaya Jeswani
 
Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Recovery (2)
Recovery (2)Recovery (2)
Recovery (2)
Jaya Jeswani
 
Olap queries
Olap queriesOlap queries
Olap queries
Jaya Jeswani
 
Recovery
RecoveryRecovery
Recovery
Jaya Jeswani
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
Jaya Jeswani
 

More from Jaya Jeswani (7)

Assignment java workshop
Assignment java workshopAssignment java workshop
Assignment java workshop
 
Assignment java workshop
Assignment java workshopAssignment java workshop
Assignment java workshop
 
Javaio
JavaioJavaio
Javaio
 
Recovery (2)
Recovery (2)Recovery (2)
Recovery (2)
 
Olap queries
Olap queriesOlap queries
Olap queries
 
Recovery
RecoveryRecovery
Recovery
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 

Recently uploaded

How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
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
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
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
 
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
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
spdendr
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
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
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
dot55audits
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Leena Ghag-Sakpal
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 

Recently uploaded (20)

How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
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
 
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
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
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
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 

Javaio

  • 1. 7-Jun-21 Simple Java I/O Part I General Principles
  • 2. 2 Prologue “They say you can hold seven plus or minus two pieces of information in your mind. I can’t remember how to open files in Java. I’ve written chapters on it. I’ve done it a bunch of times, but it’s too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. Because we open files all the time, but nobody can remember how. It is too much information to hold in your mind.” —Bruce Eckel, http://www.artima.com/intv/aboutme2.html
  • 3. 3 Streams  All modern I/O is stream-based  A stream is a connection to a source of data or to a destination for data (sometimes both)  An input stream may be associated with the keyboard  An input stream or an output stream may be associated with a file  Different streams have different characteristics:  A file has a definite length, and therefore an end  Keyboard input has no specific end
  • 4. 4 How to do I/O import java.io.*;  Open the stream  Use the stream (read, write, or both)  Close the stream
  • 5. 5 Why Java I/O is hard  Java I/O is very powerful, with an overwhelming number of options  Any given kind of I/O is not particularly difficult  The trick is to find your way through the maze of possibilities open use close
  • 6. 6 Opening a stream  There is data external to your program that you want to get, or you want to put data somewhere outside your program  When you open a stream, you are making a connection to that external place  Once the connection is made, you forget about the external place and just use the stream open use close
  • 7. 7 Example of opening a stream  A FileReader is a used to connect to a file that will be used for input: FileReader fileReader = new FileReader(fileName);  The fileName specifies where the (external) file is to be found  You never use fileName again; instead, you use fileReader open use close
  • 8. 8 Using a stream  Some streams can be used only for input, others only for output, still others for both  Using a stream means doing input from it or output to it  But it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes out open use close
  • 9. 9 Example of using a stream int charAsInt; charAsInt = fileReader.read( );  The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read  The meaning of the integer depends on the file encoding (ASCII, Unicode, other)  You can cast from int to char: char ch = (char)fileReader.read( );  FileReaderExample1.java open use close
  • 10. 10 Manipulating the input data  Reading characters as integers isn’t usually what you want to do  A BufferedReader will convert integers to characters; it can also read whole lines  The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader = new BufferedReader(fileReader); open use close
  • 11. 11 Reading lines String s; s = bufferedReader.readLine( );  A BufferedReader will return null if there is nothing more to read  FileReaderExample2.java open use close
  • 12. 12 Closing  A stream is an expensive resource  There is a limit on the number of streams that you can have open at one time  You should not have more than one stream open on the same file  You must close a stream before you can open it again  Always close your streams!  Java will normally close your streams for you when your program ends, but it isn’t good style to depend on this open use close
  • 13. 7-Jun-21 Simple Java I/O Part II LineReader and LineWriter
  • 14. 14 Text files  Text (.txt) files are the simplest kind of files  Text files can be used by many different programs  Formatted text files (such as .doc files) also contain binary formatting information  Only programs that “know the secret code” can make sense of formatted text files  Compilers, in general, work only with text
  • 15. 15 My LineReader class class LineReader { BufferedReader bufferedReader; LineReader(String fileName) {...} String readLine( ) {...} void close( ) {...} }
  • 16. 16 Basics of the LineReader constructor  Create a FileReader for the named file: FileReader fileReader = new FileReader(fileName);  Use it as input to a BufferedReader: BufferedReader bufferedReader = new BufferedReader(fileReader);  Use the BufferedReader; but first, we need to catch possible Exceptions
  • 17. 17 The full LineReader constructor LineReader(String fileName) { FileReader fileReader = null; try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println ("LineReader can’t find input file: " + fileName); e.printStackTrace( ); } bufferedReader = new BufferedReader(fileReader); }
  • 18. 18 readLine String readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null; }
  • 19. 19 close void close() { try { bufferedReader.close( ); } catch(IOException e) { } }
  • 20. 20 How did I figure that out?  I wanted to read lines from a file  I thought there might be a suitable readSomething method, so I went to the API Index  Note: Capital letters are all alphabetized before lowercase in the Index  I found a readLine method in several classes; the most promising was the BufferedReader class  The constructor for BufferedReader takes a Reader as an argument  Reader is an abstract class, but it has several implementations, including InputStreamReader  FileReader is a subclass of InputStreamReader  There is a constructor for FileReader that takes as its argument a (String) file name
  • 21. 21 The LineWriter class class LineWriter { PrintWriter printWriter; LineWriter(String fileName) {...} void writeLine(String line) {...} void close( ) {...} }
  • 22. 22 The constructor for LineWriter LineWriter(String fileName) { try { printWriter = new PrintWriter( new FileOutputStream(fileName), true); } catch(Exception e) { System.err.println("LineWriter can’t " + "use output file: " + fileName); } }
  • 23. 23 Flushing the buffer  When you put information into a buffered output stream, it goes into a buffer  The buffer may or may not be written out right away  If your program crashes, you may not know how far it got before it crashed  Flushing the buffer forces the information to be written out
  • 24. 24 PrintWriter  Buffers are automatically flushed when the program ends normally  Usually it is your responsibility to flush buffers if the program does not end normally  PrintWriter can do the flushing for you public PrintWriter(OutputStream out, boolean autoFlush)
  • 25. 25 writeLine void writeLine(String line) { printWriter.println(line); }
  • 26. 26 close void close( ) { printWriter.flush( ); try { printWriter.close( ); } catch(Exception e) { } }