SlideShare ist ein Scribd-Unternehmen logo
1 von 45
CHAPTER 6 FILES AND STREAMS
By
Sirage Zeynu (M.Tech)
School of Computing
13-04-2021 Files and Streams 2
Streams
 A stream is a sequence of data. A program uses an input stream to
read data from a source, one item at a time:
 A stream is an abstraction that either produces or consumes.
 Streams support many different kinds of data
simple bytes, primitive data types, localized characters, and
objects
 Thus, the same I/O classes and methods can be applied to any type
of device. This means that an input stream can abstract many
different kinds of input: from a disk file, a keyboard, or a network
socket.
I/O Basics
13-04-2021 Files and Streams 3
 An I/O Stream represents an input source or an output destination.
 A stream can represent many different kinds of sources and destinations,
including disk files, devices, other programs, and memory arrays.
 Streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects. Some streams
simply pass on data; others manipulate and transform the data in useful
ways.
 No matter how they work internally, all streams present the same simple
model to programs that use them
 Streams are a clean way to deal with input/output without having every
part of your code understands the difference between a keyboard and a
network, for example. Java implements streams within class hierarchies
defined in the java.io package.
Input and Output Streams(1)
13-04-2021 Files and Streams 4
Input and Output Streams(2)
A program uses an input stream to read data
from a source, one item at a time
13-04-2021 Files and Streams 5
 A program uses an output stream to write data to a destination,
one item at time
Input and Output Streams(3)
13-04-2021 Files and Streams 6
Input and Output Streams(4)
input (sources) streams
Can read from these streams Root classes of all input streams:
‱ The InputStream Class
‱ The Reader Class
Output or sink (destination) streams
Can write to these streams Root classes of all output streams:
‱ The OutputStream Class
‱ The Writer Class
13-04-2021 Files and Streams 7
Byte streams are defined by using two class hierarchies.
 At the top are two abstract classes: InputStream and OutputStream.
Each of these abstract classes has several concrete subclasses that
handle the differences between various devices, such as disk files,
network connections, and even memory buffers.
 The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement. Two of the
most important are read() and write(), which, respectively, read and
write bytes of data.
 Both methods are declared as abstract inside InputStream and
OutputStream. They are overridden by derived stream classes.
Byte Streams and Character Streams(1)
13-04-2021 Files and Streams 8
 Programs use byte streams to perform input and output of 8-
bit bytes.
 All byte stream classes are descended from InputStream and
OutputStream
 There are many byte stream classes.
 To demonstrate how byte streams work, we'll focus on
the file IO byte streams, FileInputStream and FileOutputStream
 Other kinds of byte streams are used in much the same way;
they differ mainly in the way they are constructed.
13-04-2021 Files and Streams 9
 The Java platform stores character values using Unicode conventions.
 Character stream I/O automatically translates this internal format to and
from the local character set.
 In Western locales, the local character set is usually an 8-bit superset of
ASCII.
 For most applications, I/O with character streams is no more complicated
than I/O with byte streams.
 Input and output done with stream classes automatically translates to and
from the local character set.
 A program that uses character streams in place of byte streams
automatically adapts to the local character set and is ready for
internationalization
Character Streams
13-04-2021 Files and Streams 10
 Byte streams
For binary data
Root classes for byte streams:
● The InputStream Class
● The OutputStream Class
● Both classes are abstract
Byte Streams and Character Streams(2)
Character streams
For Unicode characters
Root classes for character
streams:
● The Reader class
● The Writer class
● Both classes are abstract
13-04-2021 Files and Streams 11
Example of character streams
13-04-2021 Files and Streams 12
13-04-2021 Files and Streams 13
 System contains three predefined stream variables, in, out, and err.
 These fields are declared as public and static within System. This means
that they can be used by any other part of your program and without
reference to a specific System object.
 System.out refers to the standard output stream. By default, this is the
console.
 System.in refers to standard input, which is the keyboard by default.
System.err refers to the standard error stream, which also is the console by
default.
 However, these streams may be redirected to any compatible I/O device.
 System.in is an object of type InputStream; System.out and System.err are
objects of type PrintStream.
 These are byte streams, even though they typically are used to read and
write characters from and to the console.
The Predefined Streams
13-04-2021 Files and Streams 14
 In Java, console input is accomplished by reading from
System.in
 To obtain a character- based stream that is attached to the
console, you wrap System.in
 in a BufferedReader object, to create a character stream.
 BuffereredReader supports a buffered input stream. Its most
commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of
BufferedReader that is being created.
Reading Console Input
13-04-2021 Files and Streams 15
Reading Characters
13-04-2021 Files and Streams 16
 To read a string from the keyboard, use the version of
readLine() that is a member of the BufferedReader class.
Its general form is shown here:
 String readLine() throws IOException As you can see, it
returns a String object.
 The following program demonstrates BufferedReader and the
readLine() method; the program reads and displays lines of
text until you enter the word “stop”:
Reading Strings
13-04-2021 Files and Streams 17
Example Reading Strings
13-04-2021 Files and Streams 18
 Console output is most easily accomplished with print() and
println()
 These methods are defined by the class PrintStream (which is
the type of the object referenced by System.out).
 Even though System.out is a byte stream, using it for simple
program output is still acceptable.
 Because PrintStream is an output stream derived from
OutputStream, it also implements the low-level method write().
Thus, write() can be used to write to the console.
 The simplest form of write() defined by PrintStream is shown
here:
Writing Console Output
13-04-2021 Files and Streams 19
void write(int byteval)
This method writes to the stream the byte specified by byteval.
Although byteval is declared as an integer, only the low-order
eight bits are written. Here is a short example that uses write()
to output the character “A” followed by a newline to the screen:
You will not often use write() to perform console output (although doing so might be useful in some situations),
because print() and println() are substantially easier to use.
13-04-2021 Files and Streams 20
The streams used most often are the standard input (the
keyboard) and the standard output (the CRT display).
Alternatively, standard input can arrive from a disk file using
"input redirection", and standard output can be written to a disk
file using "output redirection".
A more flexible mechanism to read or write disk files is
available through Java's file streams.
File Streams(1)
13-04-2021 Files and Streams 21
The two file streams presented here are
The file reader stream
The file writer stream.
 As with the standard I/O streams, we access these through objects
of the associated class,
 namely the FileReader class and the FileWriter class. Unlike the
standard I/O streams, however, we must explicitly "open" a file
stream before using it.
 After using a file stream, it is good practice to "close" the stream,
although, strictly speaking, this is not necessary as all streams are
automatically closed when a program terminates.
File Streams(2)
13-04-2021 Files and Streams 22
 To open a file output stream to which text can be written, we
use the FileWriter class.
 As always, it is best to buffer the output. The following sets up
a buffered file writer stream named outFile to write text into a
file named save.txt:
Writing Files
PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter("save.txt"));
The object outFile, above, is of the PrintWriter class, just like System.out.
If a string, s, contains some text, it is written to the file as follows:
outFile.println(s);
When finished, the file is closed as expected:
outFile.close();
13-04-2021 Files and Streams 23
 FileWriter is useful to create a file writing characters into it.
 This class inherits from the OutputStream class.
 The constructors of this class assume that the default
character encoding and the default byte-buffer size are
acceptable.
 To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
 FileWriter is meant for writing streams of characters.
 For writing streams of raw bytes, consider using a
FileOutputStream.
 FileWriter creates the output file , if it is not present already.
FileWriter
13-04-2021 Files and Streams 24
 FileWriter(File file) – Constructs a FileWriter object given a File object.
 FileWriter (File file, boolean append) – constructs a FileWriter object
given a File object.
 FileWriter (FileDescriptor fd) – constructs a FileWriter object associated
with a file descriptor.
 FileWriter (String fileName) – constructs a FileWriter object given a file
name.
 FileWriter (String fileName, Boolean append) – Constructs a FileWriter
object given a file name with a Boolean indicating whether or not to
append the data written.

Constructors
13-04-2021 Files and Streams 25
public void write (char c) throws IOException – Writes a single
character.
 public void write (char [] str) throws IOException – Writes an array
of characters.
 public void write(String str)throws IOException – Writes a string.
 public void write(String str,int off,int len)throws IOException –
Writes a portion of a string. Here off is offset from which to start
writing characters and len is number of character to write.
 public void flush() throws IOException flushes the stream
 public void close() throws IOException flushes the stream first and
then closes the writer.
Methods
13-04-2021 Files and Streams 26
Following program depicts how to create a text file using FileWriter
13-04-2021 Files and Streams 27
 Let's begin with the FileReader class.
As with keyboard input, it is most efficient to work through the
BufferedReader
If we wish to read text from a file named foo.txt, it is opened as a
file input stream as follows:
The line above "opens" foo.txt as a FileReader object and passes it
to the constructor of the BufferedReader class.
The result is a BufferedReader object named inputFile.
Reading Files
BufferedReader inputFile = new BufferedReader(new FileReader(“foo.txt”))
13-04-2021 Files and Streams 28
 FileReader is useful to read data in the form of characters from
a ‘text’ file.
 This class inherit from the InputStreamReader Class.
 The constructors of this class assume that the default character
encoding and the default byte-buffer size are appropriate.
 To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
 FileReader is meant for reading streams of characters.
 For reading streams of raw bytes, consider using a
FileInputStream.
FileReader
13-04-2021 Files and Streams 29
 FileReader(File file) – Creates a FileReader , given the File
to read from
 FileReader(FileDescripter fd) – Creates a new FileReader ,
given the FileDescripter to read from
 FileReader(String fileName) – Creates a new FileReader ,
given the name of the file to read from
Constructors
13-04-2021 Files and Streams 30
 public int read () throws IOException – Reads a single character. This
method will block until a character is available, an I/O error occurs, or the
end of the stream is reached.
 public int read(char[] cbuff) throws IOException – Reads characters
into an array. This method will block until some input is available, an I/O
error occurs, or the end of the stream is reached.
 public abstract int read(char[] buff, int off, int len) throws
IOException –Reads characters into a portion of an array. This method
will block until some input is available, an I/O error occurs, or the end of
the stream is reached.
public void close() throws IOException closes the reader.
 public long skip(long n) throws IOException –Skips characters. This
method will block until some characters are available, an I/O error occurs,
or the end of the stream is reached.
Methods:
13-04-2021 Files and Streams 31
Following program depicts how to read from the ‘text’ file using FileReader
13-04-2021 Files and Streams 32
a simple Java program to open a text file called temp.txt and to count the number of lines and characters in the
file.
13-04-2021 Files and Streams 33
 There are several ways to read a plain text file in Java
e.g. you can use FileReader, BufferedReader or Scanner to read
a text file.
 Every utility provides something special
e.g. BufferedReader provides buffering of data for fast reading,
and Scanner provides parsing ability.
 We can also use both BufferReader and Scanner to read a text
file line by line in Java.
Different ways of Reading a text file in Java
13-04-2021 Files and Streams 34
1. Using FileReader class: Convenience class for reading
character files. The constructors of this class assume that the
default character encoding and the default byte-buffer size are
appropriate.
Constructors defined in this class are:
// Creates a new FileReader, given the File to read from. FileReader(File file)
// Creates a new FileReader, given the FileDescriptor to read from.
FileReader(FileDescriptor fd)
// Creates a new FileReader, given the name of the file to read from. FileReader(String
fileName)
Here are some of the many ways of reading files(1)
13-04-2021 Files and Streams 35
Java Program to illustrate reading from FileReader using FileReader
13-04-2021 Files and Streams 36
2. Using BufferedReader: This method reads text from a
character-input stream.
It does buffering for efficient reading of characters, arrays, and
lines.
The buffer size may be specified, or the default size may be used.
The default is large enough for most purposes.
 In general, each read request made of a Reader causes a
corresponding read request to be made of the underlying
character or byte stream.
For example,
BufferedReader in = new BufferedReader(Reader in, int size);
Here are some of the many ways of reading files(2)
13-04-2021 Files and Streams 37
Java Program to illustrate reading from FileReader using BufferedReader
13-04-2021 Files and Streams 38
3. Using Scanner class: A simple text scanner which can parse
primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may
then be converted into values of different types using the
various next methods.
Here are some of the many ways of reading files(3)
13-04-2021 Files and Streams 39
Java Program to illustrate reading from Text File using Scanner Class
13-04-2021 Files and Streams 40
Java provides functions to move files between directories. Two
ways to achieve this are described here.
The first method utilizes Files package for moving while the
other method first copies the file to destination and then deletes
the original copy from the source.
Moving a file from one directory to another using Java
13-04-2021 Files and Streams 41
 Renaming and moving the file permanently to a new location.
Syntax:
 public static Path move(Path source, Path target,
CopyOption..options) throws IOException
Parameters:
 source - the path to the file to move
 target - the path to the target file (may be associated with a
different provider to the source path)
 options - options specifying how the move should be done
Returns: the path to the target file
1. Using Files.Path move() method:
13-04-2021 Files and Streams 42
13-04-2021 Files and Streams 43
 Copying the file and deleting the original file using these two
methods.
Syntax of renameTo():
 public boolean renameTo(File dest)
 Description: Renames the file denoted by this abstract path
name.
 Parameters: dest - The new abstract path name for the
named file
 Returns: true if and only if the renaming succeeded; false
otherwise
 public boolean delete() Deletes the file or directory denoted
by this abstract path name.
2. Using Java.io.File.renameTo() and Java.io.File.delete() methods:
13-04-2021 Files and Streams 44
Java program to illustrate Copying the file and deleting the original file
13-04-2021 Files and Streams 45

Weitere Àhnliche Inhalte

Was ist angesagt?

SessionFive_ImportingandExportingData
SessionFive_ImportingandExportingDataSessionFive_ImportingandExportingData
SessionFive_ImportingandExportingData
Hellen Gakuruh
 
2004 snug-boston-presentation system-verilog_fifo_channel
2004 snug-boston-presentation system-verilog_fifo_channel2004 snug-boston-presentation system-verilog_fifo_channel
2004 snug-boston-presentation system-verilog_fifo_channel
AkhilReddy Sankati
 

Was ist angesagt? (19)

Linking in MS-Dos System
Linking in MS-Dos SystemLinking in MS-Dos System
Linking in MS-Dos System
 
MASM -UNIT-III
MASM -UNIT-IIIMASM -UNIT-III
MASM -UNIT-III
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
 
02 copy file_fill_sp16
02 copy file_fill_sp1602 copy file_fill_sp16
02 copy file_fill_sp16
 
Microprocessor 8086 notes
Microprocessor 8086 notesMicroprocessor 8086 notes
Microprocessor 8086 notes
 
Systematic error codes implimentation for matched data encoded 47405
Systematic error codes implimentation for matched data encoded 47405Systematic error codes implimentation for matched data encoded 47405
Systematic error codes implimentation for matched data encoded 47405
 
Printer Class
Printer ClassPrinter Class
Printer Class
 
Word processing
Word processingWord processing
Word processing
 
Instruction Set and Assembly Language Programming
Instruction Set and Assembly Language ProgrammingInstruction Set and Assembly Language Programming
Instruction Set and Assembly Language Programming
 
SessionFive_ImportingandExportingData
SessionFive_ImportingandExportingDataSessionFive_ImportingandExportingData
SessionFive_ImportingandExportingData
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Addressing
AddressingAddressing
Addressing
 
8086 memory segmentation
8086 memory segmentation8086 memory segmentation
8086 memory segmentation
 
8086 Microprocessor
8086 Microprocessor 8086 Microprocessor
8086 Microprocessor
 
2004 snug-boston-presentation system-verilog_fifo_channel
2004 snug-boston-presentation system-verilog_fifo_channel2004 snug-boston-presentation system-verilog_fifo_channel
2004 snug-boston-presentation system-verilog_fifo_channel
 
Database driven web pages
Database driven web pagesDatabase driven web pages
Database driven web pages
 
Application Layer
Application LayerApplication Layer
Application Layer
 
Basics of 8086
Basics of 8086Basics of 8086
Basics of 8086
 
[ASM] Lab2
[ASM] Lab2[ASM] Lab2
[ASM] Lab2
 

Ähnlich wie Chapter 6

UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
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
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
ssuser9d7049
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 

Ähnlich wie Chapter 6 (20)

Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 
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
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
Data file handling
Data file handlingData file handling
Data file handling
 
Io streams
Io streamsIo streams
Io streams
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 

Mehr von siragezeynu (12)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
6 database
6 database 6 database
6 database
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Lab4
Lab4Lab4
Lab4
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
 

KĂŒrzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
Christopher Logan Kennedy
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

KĂŒrzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Chapter 6

  • 1. CHAPTER 6 FILES AND STREAMS By Sirage Zeynu (M.Tech) School of Computing
  • 2. 13-04-2021 Files and Streams 2 Streams  A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time:  A stream is an abstraction that either produces or consumes.  Streams support many different kinds of data simple bytes, primitive data types, localized characters, and objects  Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. I/O Basics
  • 3. 13-04-2021 Files and Streams 3  An I/O Stream represents an input source or an output destination.  A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.  Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.  No matter how they work internally, all streams present the same simple model to programs that use them  Streams are a clean way to deal with input/output without having every part of your code understands the difference between a keyboard and a network, for example. Java implements streams within class hierarchies defined in the java.io package. Input and Output Streams(1)
  • 4. 13-04-2021 Files and Streams 4 Input and Output Streams(2) A program uses an input stream to read data from a source, one item at a time
  • 5. 13-04-2021 Files and Streams 5  A program uses an output stream to write data to a destination, one item at time Input and Output Streams(3)
  • 6. 13-04-2021 Files and Streams 6 Input and Output Streams(4) input (sources) streams Can read from these streams Root classes of all input streams: ‱ The InputStream Class ‱ The Reader Class Output or sink (destination) streams Can write to these streams Root classes of all output streams: ‱ The OutputStream Class ‱ The Writer Class
  • 7. 13-04-2021 Files and Streams 7 Byte streams are defined by using two class hierarchies.  At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that handle the differences between various devices, such as disk files, network connections, and even memory buffers.  The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read() and write(), which, respectively, read and write bytes of data.  Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes. Byte Streams and Character Streams(1)
  • 8. 13-04-2021 Files and Streams 8  Programs use byte streams to perform input and output of 8- bit bytes.  All byte stream classes are descended from InputStream and OutputStream  There are many byte stream classes.  To demonstrate how byte streams work, we'll focus on the file IO byte streams, FileInputStream and FileOutputStream  Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.
  • 9. 13-04-2021 Files and Streams 9  The Java platform stores character values using Unicode conventions.  Character stream I/O automatically translates this internal format to and from the local character set.  In Western locales, the local character set is usually an 8-bit superset of ASCII.  For most applications, I/O with character streams is no more complicated than I/O with byte streams.  Input and output done with stream classes automatically translates to and from the local character set.  A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization Character Streams
  • 10. 13-04-2021 Files and Streams 10  Byte streams For binary data Root classes for byte streams: ● The InputStream Class ● The OutputStream Class ● Both classes are abstract Byte Streams and Character Streams(2) Character streams For Unicode characters Root classes for character streams: ● The Reader class ● The Writer class ● Both classes are abstract
  • 11. 13-04-2021 Files and Streams 11 Example of character streams
  • 12. 13-04-2021 Files and Streams 12
  • 13. 13-04-2021 Files and Streams 13  System contains three predefined stream variables, in, out, and err.  These fields are declared as public and static within System. This means that they can be used by any other part of your program and without reference to a specific System object.  System.out refers to the standard output stream. By default, this is the console.  System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default.  However, these streams may be redirected to any compatible I/O device.  System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.  These are byte streams, even though they typically are used to read and write characters from and to the console. The Predefined Streams
  • 14. 13-04-2021 Files and Streams 14  In Java, console input is accomplished by reading from System.in  To obtain a character- based stream that is attached to the console, you wrap System.in  in a BufferedReader object, to create a character stream.  BuffereredReader supports a buffered input stream. Its most commonly used constructor is shown here: BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reading Console Input
  • 15. 13-04-2021 Files and Streams 15 Reading Characters
  • 16. 13-04-2021 Files and Streams 16  To read a string from the keyboard, use the version of readLine() that is a member of the BufferedReader class. Its general form is shown here:  String readLine() throws IOException As you can see, it returns a String object.  The following program demonstrates BufferedReader and the readLine() method; the program reads and displays lines of text until you enter the word “stop”: Reading Strings
  • 17. 13-04-2021 Files and Streams 17 Example Reading Strings
  • 18. 13-04-2021 Files and Streams 18  Console output is most easily accomplished with print() and println()  These methods are defined by the class PrintStream (which is the type of the object referenced by System.out).  Even though System.out is a byte stream, using it for simple program output is still acceptable.  Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write(). Thus, write() can be used to write to the console.  The simplest form of write() defined by PrintStream is shown here: Writing Console Output
  • 19. 13-04-2021 Files and Streams 19 void write(int byteval) This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write() to output the character “A” followed by a newline to the screen: You will not often use write() to perform console output (although doing so might be useful in some situations), because print() and println() are substantially easier to use.
  • 20. 13-04-2021 Files and Streams 20 The streams used most often are the standard input (the keyboard) and the standard output (the CRT display). Alternatively, standard input can arrive from a disk file using "input redirection", and standard output can be written to a disk file using "output redirection". A more flexible mechanism to read or write disk files is available through Java's file streams. File Streams(1)
  • 21. 13-04-2021 Files and Streams 21 The two file streams presented here are The file reader stream The file writer stream.  As with the standard I/O streams, we access these through objects of the associated class,  namely the FileReader class and the FileWriter class. Unlike the standard I/O streams, however, we must explicitly "open" a file stream before using it.  After using a file stream, it is good practice to "close" the stream, although, strictly speaking, this is not necessary as all streams are automatically closed when a program terminates. File Streams(2)
  • 22. 13-04-2021 Files and Streams 22  To open a file output stream to which text can be written, we use the FileWriter class.  As always, it is best to buffer the output. The following sets up a buffered file writer stream named outFile to write text into a file named save.txt: Writing Files PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter("save.txt")); The object outFile, above, is of the PrintWriter class, just like System.out. If a string, s, contains some text, it is written to the file as follows: outFile.println(s); When finished, the file is closed as expected: outFile.close();
  • 23. 13-04-2021 Files and Streams 23  FileWriter is useful to create a file writing characters into it.  This class inherits from the OutputStream class.  The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.  To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.  FileWriter is meant for writing streams of characters.  For writing streams of raw bytes, consider using a FileOutputStream.  FileWriter creates the output file , if it is not present already. FileWriter
  • 24. 13-04-2021 Files and Streams 24  FileWriter(File file) – Constructs a FileWriter object given a File object.  FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.  FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.  FileWriter (String fileName) – constructs a FileWriter object given a file name.  FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.  Constructors
  • 25. 13-04-2021 Files and Streams 25 public void write (char c) throws IOException – Writes a single character.  public void write (char [] str) throws IOException – Writes an array of characters.  public void write(String str)throws IOException – Writes a string.  public void write(String str,int off,int len)throws IOException – Writes a portion of a string. Here off is offset from which to start writing characters and len is number of character to write.  public void flush() throws IOException flushes the stream  public void close() throws IOException flushes the stream first and then closes the writer. Methods
  • 26. 13-04-2021 Files and Streams 26 Following program depicts how to create a text file using FileWriter
  • 27. 13-04-2021 Files and Streams 27  Let's begin with the FileReader class. As with keyboard input, it is most efficient to work through the BufferedReader If we wish to read text from a file named foo.txt, it is opened as a file input stream as follows: The line above "opens" foo.txt as a FileReader object and passes it to the constructor of the BufferedReader class. The result is a BufferedReader object named inputFile. Reading Files BufferedReader inputFile = new BufferedReader(new FileReader(“foo.txt”))
  • 28. 13-04-2021 Files and Streams 28  FileReader is useful to read data in the form of characters from a ‘text’ file.  This class inherit from the InputStreamReader Class.  The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.  To specify these values yourself, construct an InputStreamReader on a FileInputStream.  FileReader is meant for reading streams of characters.  For reading streams of raw bytes, consider using a FileInputStream. FileReader
  • 29. 13-04-2021 Files and Streams 29  FileReader(File file) – Creates a FileReader , given the File to read from  FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from  FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from Constructors
  • 30. 13-04-2021 Files and Streams 30  public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.  public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.  public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. public void close() throws IOException closes the reader.  public long skip(long n) throws IOException –Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached. Methods:
  • 31. 13-04-2021 Files and Streams 31 Following program depicts how to read from the ‘text’ file using FileReader
  • 32. 13-04-2021 Files and Streams 32 a simple Java program to open a text file called temp.txt and to count the number of lines and characters in the file.
  • 33. 13-04-2021 Files and Streams 33  There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file.  Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.  We can also use both BufferReader and Scanner to read a text file line by line in Java. Different ways of Reading a text file in Java
  • 34. 13-04-2021 Files and Streams 34 1. Using FileReader class: Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. Constructors defined in this class are: // Creates a new FileReader, given the File to read from. FileReader(File file) // Creates a new FileReader, given the FileDescriptor to read from. FileReader(FileDescriptor fd) // Creates a new FileReader, given the name of the file to read from. FileReader(String fileName) Here are some of the many ways of reading files(1)
  • 35. 13-04-2021 Files and Streams 35 Java Program to illustrate reading from FileReader using FileReader
  • 36. 13-04-2021 Files and Streams 36 2. Using BufferedReader: This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.  In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. For example, BufferedReader in = new BufferedReader(Reader in, int size); Here are some of the many ways of reading files(2)
  • 37. 13-04-2021 Files and Streams 37 Java Program to illustrate reading from FileReader using BufferedReader
  • 38. 13-04-2021 Files and Streams 38 3. Using Scanner class: A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. Here are some of the many ways of reading files(3)
  • 39. 13-04-2021 Files and Streams 39 Java Program to illustrate reading from Text File using Scanner Class
  • 40. 13-04-2021 Files and Streams 40 Java provides functions to move files between directories. Two ways to achieve this are described here. The first method utilizes Files package for moving while the other method first copies the file to destination and then deletes the original copy from the source. Moving a file from one directory to another using Java
  • 41. 13-04-2021 Files and Streams 41  Renaming and moving the file permanently to a new location. Syntax:  public static Path move(Path source, Path target, CopyOption..options) throws IOException Parameters:  source - the path to the file to move  target - the path to the target file (may be associated with a different provider to the source path)  options - options specifying how the move should be done Returns: the path to the target file 1. Using Files.Path move() method:
  • 42. 13-04-2021 Files and Streams 42
  • 43. 13-04-2021 Files and Streams 43  Copying the file and deleting the original file using these two methods. Syntax of renameTo():  public boolean renameTo(File dest)  Description: Renames the file denoted by this abstract path name.  Parameters: dest - The new abstract path name for the named file  Returns: true if and only if the renaming succeeded; false otherwise  public boolean delete() Deletes the file or directory denoted by this abstract path name. 2. Using Java.io.File.renameTo() and Java.io.File.delete() methods:
  • 44. 13-04-2021 Files and Streams 44 Java program to illustrate Copying the file and deleting the original file
  • 45. 13-04-2021 Files and Streams 45

Hinweis der Redaktion

  1. Reading Console Input In Java, console input is accomplished by reading from System.in. To obtain a character- based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is shown here: BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in. Reading Characters To read a character from a BufferedReader, use read(). The version of read() that we will be using is int read( ) throws IOException Each time that read() is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. As you can see, it can throw an IOException.
  2. Reading and writing take place character by character, which increases the number of I/O operations and effects performance of the system.BufferedWriter can be used along with FileWriter to improve speed of execution
  3. A sample dialogue with this file follows (user input is underlined): PROMPT>java FileWrite Enter some text on the keyboard... (^z to terminate) Happy new year! ^z PROMPT> Note that ^z means hold the Control key down while pressing z. entered.) (On unix systems, ^d must be If the program is immiately run again, then the following dialogue results: Java Primer StreamClassesFileIO-8 © Scott MacKenzie PROMPT>java FileWrite Overwrite junk.txt (y/n)? y Enter some text on the keyboard... (^z to terminate) Happy birthday! ^z PROMPT> Since the file junk.txt was created on the first pass, it already exists on the second. Our code (see lines 15-22) provides a reasonable safety check before proceeding. Since the user entered “y”, the program proceeds; however, the previous contents are overwritten. There are several ways to demonstrate the “exceptional conditions” that may arise when working with disk files, and these are worth considering. Once the file junk.txt exists, make it “read only” and re-run FileWrite The program will terminate with the “access is denied” message 1 noted earlier. Another interesting demonstration is to open junk.txt in an editor, and then exectute FileWrite. The behaviour may vary from one editor to the next, but we’ll leave this for you to explore. Here’s a programming challenge for you: Make a copy of FileWrite.java and name the new file FileWrite2.java. Modify the program such that junk.txt is opened in append mode. Compile the new program, then run it a few times to convince yourself that the file contents are preserved from one invocation to the next.