SlideShare a Scribd company logo
1 of 32
I/O Streams In Java
I/O Streams
The java.io package contains nearly every class we might ever need to perform
input and output (I/O) in Java
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.
A stream can be defined as a sequence of data. There are two kinds of Streams
−
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.
Reading information into a program.
A program uses an input stream to read data from a source,
one item at a time:
Writing information from a program.
A program uses an output stream to write data to
a destination, one item at time:
Standard Streams
Java provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
A list of the various print functions that we use to output statements
print():This method in Java is used to display a text on the console. This text is
passed as the parameter to this method in the form of String. This method
prints the text on the console and the cursor remains at the end of the text at
the console. The next printing takes place from just here.
Syntax: System.out.print(parameter);
println(): This method in Java is also used to display a text on the console.
It prints the text on the console and the cursor moves to the start of the
next line at the console. The next printing takes place from the next line.
Syntax:System.out.println(parameter);
printf():This is the easiest of all methods as this is similar to printf in C.
Note that System.out.print() and System.out.println() take a single
argument, but printf() may take multiple arguments. This is used to
format the output in Java.
System.out.printf("Formatted to "+ "specific width: n = %.4fn", // this
will print it up to // 2 decimal places);
System.err: This is the standard error stream that is used to output
all the error data that a program might throw, on a computer screen
or any standard output device. This stream also uses all the 3
functions to output the error data
• print()
• println()
• printf()
Types of Streams
Depending on the type of operations, streams can be divided into two primary classes:
• Input Stream : These streams are used to read data that must be taken as an input from a source
array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.
• Output Stream: These streams are used to write data as outputs into
an array or file or any output peripheral device. For eg.,
FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
Depending on the types of file, Streams can be divided into two
primary classes ByteStream and CharacterStream
ByteStream: This is used to process data byte by byte (8 bits).
Though it has many classes, the FileInputStream and the
FileOutputStream are the most popular ones. The
FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination.
CharacterStream: This stream is used to perform input and
output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used
classes are, FileReader and FileWriter.
VARIOUS BYTESTREAM CLASSES
BufferedInputStream
This class provides methods to read raw bytes from the buffer.
DataInputStream
It contains method for reading java standard datatypes.
FileInputStream
This class provides methods to read bytes from the file.
InputStream
This is an abstract class that describes stream input.
PrintStream
This contains the most used print() and println() method
BufferedOutputStream
This is used for Buffered Output Stream.
DataOutputStream
This contains method for writing java standard data types.
FileOutputStream
This is used to write to a file.
OutputStream
This is an abstract class that describe stream output.
Hierarchy of classes to deal with Input and Output
streams
VARIOUS CHARACTERSTREAM CLASSES
BufferedReader
It is used to handle buffered input stream, reads characters (text).
FileReader
This is an input stream that reads from file.
InputStreamReader
This input stream is used to translate byte to character.
OutputStreamReader
This output stream is used to translate character to byte.
Reader
This is an abstract class that define character stream input.
PrintWriter
This contains the most used print() and println() method
Writer
This is an abstract class that define character stream output.
BufferedWriter
This is used to handle buffered output stream.
FileWriter
This is used to output stream that writes to file.
BufferedReader
• Java Reader is an abstract class for reading character streams. The
Java BufferedReader class is a subclass of the Java Reader class
• The Java BufferedReader class, java.io.BufferedReader, provides buffering for our
Java Reader instances.
• Java BufferedReader reads a larger block (array) at a time.
• The Java BufferedReader is similar to the BufferedInputStream but they are not exactly the
same.
• The main difference between BufferedReader and BufferedInputStream is
that BufferedReader reads characters(text), whereas the BufferedInputStream reads raw
bytes.
The BufferedReader class of Java is used to read the stream of characters from the specified source
(character-input stream). The constructor of this class accepts an InputStream object as a parameter.
This class provides methods named read() and readLine() which reads and returns the character
and next line from the source (respectively) and returns them.
• Instantiate an InputStreamReader class bypassing your InputStream object as a parameter.
• Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a
parameter.
• Now, read data from the current reader as String using the readLine() or read() method.
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.in is an InputStream which is typically connected to keyboard input of console programs.
DataInputStream Class
Java DataInputStream class allows an application to read primitive data (int, float, long etc.)from the
input stream in a machine-independent way.
Declaration for java.io.DataInputStream class
public class DataInputStream extends FilterInputStream implements DataInput
Wrap an InputStream in a DataInputStream and then you can read Java primitives via
the DataInputStream.
That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes.
Create a DataInputStream
We create a Java DataInputStream via its constructor.
Pass an InputStream as parameter from which the primitive data types are to be read
DataInputStream dataInputStream = new DataInputStream( new
FileInputStream("data/data.bin"));
1.First a DataInputStream is created with a FileInputStream as source for its data.
2. Java primitives are read from the DataInputStream.
Java DataInputStream class Methods
Method Description
int read(byte[] b) It is used to read the number of bytes
from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data
from the input stream.
int readInt() It is used to read input bytes and
return an int value.
byte readByte() It is used to read and return the one
input byte.
char readChar() It is used to read two input bytes and
returns a char value.
double readDouble() It is used to read eight input bytes and
returns a double value.
boolean readBoolean()
It is used to read one input byte and
return true if byte is non zero, false if
byte is zero.
int skipBytes(int x)
It is used to skip over x bytes of data
from the input stream.
String readUTF() It is used to read a string that has been
encoded using the UTF-8 format.
void readFully(byte[] b)
It is used to read bytes from the input
stream and store them into the
buffer array.
Difference between DataInputStream and BufferedReader
• The DataInputStream works with the binary data, while the BufferedReader work with
character data.
• DataInputStream is a kind of InputStream to read data directly as primitive data types.
• BufferedInputStream is a kind of inputStream that reads data from a stream and uses a
buffer to optimize speed access to data.
• DataInputStream consumes less amount of memory space being it is binary stream, where
as BufferedReader consumes more memory space being it is character stream.
• The data to be handled is limited in DataInputStream, where as the number of characters to
be handled has wide scope in BufferedReader.
• All primitive data types can be handled by using the corresponding methods in
DataInputStream class, while only string data can be read from BufferedReader class and they
need to be parsed into the respective primitives.
Scanner Class in Java
• The Scanner class is used to get user input, and it is found in the java.util package.
• It is used for obtaining the input of the primitive types like int, double, etc. and
strings.
• To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream. We may pass an object of class File if we want to read input
from a file. A Scanner breaks its input into tokens using a delimiter pattern.
• The resulting tokens may then be converted into values of different types using the
various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
• You can declare scanner type object say ‘sc’
• The Scanner class constructor, which takes an InputStream object (i.e., System.in) as a parameter. The
System.in specifies the standard console keyboard input.
Input Types
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Difference between Scanner and BufferedReader
• Scanner class can be used for user input by importing from java.util package.
• BufferedReader class can be used by importing from java.io package.
• Buffered Reader reads the input and buffers it.
• It hasn’t multiple functions like reading integer or character or long.
• Buffered reader just reads a line.
• Scanner on the other hand is formatted input.
• It has ability to read character, integer, long, etc.
• It reads the input and processes it accordingly.
• Scanner class uses regular expression in parsing the strings, by default, white space gets set as a delimiter,
but you can set any other delimiter.
• Scanner is slower than BufferedReader
FileInputStream Class
• The FileInputStream class of the java.io package can be used to read contents of a file as a stream of bytes.
• The Java FileInputStream class is a subclass of Java InputStream.
• To read the contents from the file, first make an object of FileInputStream class and specify the file name as an
argument to the constructor:
1. Using the path to file
FileInputStream input = new FileInputStream(StringPath);
2. Using an object of the file
FileInputStream input = new FileInputStream(File fileObject);
Methods of FileInputStream
• read() - reads a single byte from the file
• read(byte[] array) - reads the bytes from the file and stores in the specified array
• read(byte[] array, int start, int length) - reads the number of bytes equal to length from
the file and stores in the specified array starting from the position start
• available()-To get the number of available bytes, we can use the available() method.
Convert FileInputStream to Reader
• The Java FileInputStream is a byte based stream of data.
• We can convert a Java FileInputStream to a Java Reader using the Java
InputStreamReader.
• The Java InputStreamReader class is thus a subclass of the Java Reader class.
• InputStreamReader class, wraps a Java InputStream, thereby turning the byte
based InputStream into a character based Reader.
• The Java InputStreamReader is often used to read characters from file
Example
InputStream inputStream = new FileInputStream("c:datainput.txt"); Reader
inputStreamReader = new InputStreamReader(inputStream);
First creates a FileInputStream and then wraps it in an InputStreamReader. Second, the
FileOutputStream in Java
• The FileOutputStream class of the java.io package can be used to write data (in bytes)
to the files. In order to create a file output stream, we must import
the java.io.FileOutputStream package first.
we can create a file output stream in Java
• 1. Using the path to file
FileOutputStream output = new FileOutputStream(String path);
• 2. Using an object of the file
FileOutputStream output = new FileOutputStream(File fileObject);
Methods of FileOutputStream
• write() - writes the single byte to the file output stream
• write(byte[] array) - writes the bytes from the specified array to the output stream
• write(byte[] array, int start, int length) - writes the number of bytes equal to length to
the output stream from an array starting from the position start
• getBytes() -converts a string into an array of bytes.
• flush() -To clear the output stream, we can use the flush() method. This method forces
the output stream to write all data to the destination.
• close()-It is used to closes the file output stream.

More Related Content

Similar to IO Streams In Java: A Guide To Input/Output Operations

Java Input and Output
Java Input and OutputJava Input and Output
Java Input and OutputDucat India
 
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 & Outputphanleson
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxSadhilAggarwal
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfhemanth248901
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/ONem Sothea
 
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 argumentsKuntal Bhowmick
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in javaJyoti Verma
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 

Similar to IO Streams In Java: A Guide To Input/Output Operations (20)

Java Input and Output
Java Input and OutputJava Input and Output
Java Input and Output
 
Io streams
Io streamsIo streams
Io 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
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
JAVA (UNIT 3)
JAVA (UNIT 3)JAVA (UNIT 3)
JAVA (UNIT 3)
 
Io Streams
Io StreamsIo Streams
Io Streams
 
Java stream
Java streamJava stream
Java stream
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
Java I/O
Java I/OJava I/O
Java I/O
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
 
Input output streams
Input output streamsInput output streams
Input output streams
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
 
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
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Basic IO
Basic IOBasic IO
Basic IO
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 

Recently uploaded

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 

Recently uploaded (20)

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 

IO Streams In Java: A Guide To Input/Output Operations

  • 2. I/O Streams The java.io package contains nearly every class we might ever need to perform input and output (I/O) in Java 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. A stream can be defined as a sequence of data. There are two kinds of Streams − • InPutStream − The InputStream is used to read data from a source. • OutPutStream − The OutputStream is used for writing data to a destination.
  • 3.
  • 4. Reading information into a program. A program uses an input stream to read data from a source, one item at a time:
  • 5. Writing information from a program. A program uses an output stream to write data to a destination, one item at time:
  • 6. Standard Streams Java provides the following three standard streams − • Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in. • Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out. A list of the various print functions that we use to output statements print():This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here. Syntax: System.out.print(parameter);
  • 7. println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line. Syntax:System.out.println(parameter); printf():This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java. System.out.printf("Formatted to "+ "specific width: n = %.4fn", // this will print it up to // 2 decimal places);
  • 8. System.err: This is the standard error stream that is used to output all the error data that a program might throw, on a computer screen or any standard output device. This stream also uses all the 3 functions to output the error data • print() • println() • printf()
  • 9. Types of Streams Depending on the type of operations, streams can be divided into two primary classes: • Input Stream : These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
  • 10. • Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.
  • 11. Depending on the types of file, Streams can be divided into two primary classes ByteStream and CharacterStream ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. CharacterStream: This stream is used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter.
  • 12. VARIOUS BYTESTREAM CLASSES BufferedInputStream This class provides methods to read raw bytes from the buffer. DataInputStream It contains method for reading java standard datatypes. FileInputStream This class provides methods to read bytes from the file. InputStream This is an abstract class that describes stream input. PrintStream This contains the most used print() and println() method
  • 13. BufferedOutputStream This is used for Buffered Output Stream. DataOutputStream This contains method for writing java standard data types. FileOutputStream This is used to write to a file. OutputStream This is an abstract class that describe stream output.
  • 14. Hierarchy of classes to deal with Input and Output streams
  • 15. VARIOUS CHARACTERSTREAM CLASSES BufferedReader It is used to handle buffered input stream, reads characters (text). FileReader This is an input stream that reads from file. InputStreamReader This input stream is used to translate byte to character. OutputStreamReader This output stream is used to translate character to byte. Reader This is an abstract class that define character stream input.
  • 16. PrintWriter This contains the most used print() and println() method Writer This is an abstract class that define character stream output. BufferedWriter This is used to handle buffered output stream. FileWriter This is used to output stream that writes to file.
  • 17. BufferedReader • Java Reader is an abstract class for reading character streams. The Java BufferedReader class is a subclass of the Java Reader class • The Java BufferedReader class, java.io.BufferedReader, provides buffering for our Java Reader instances. • Java BufferedReader reads a larger block (array) at a time. • The Java BufferedReader is similar to the BufferedInputStream but they are not exactly the same. • The main difference between BufferedReader and BufferedInputStream is that BufferedReader reads characters(text), whereas the BufferedInputStream reads raw bytes.
  • 18. The BufferedReader class of Java is used to read the stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter. This class provides methods named read() and readLine() which reads and returns the character and next line from the source (respectively) and returns them. • Instantiate an InputStreamReader class bypassing your InputStream object as a parameter. • Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter. • Now, read data from the current reader as String using the readLine() or read() method. BufferedReader reader =new BufferedReader(new InputStreamReader(System.in)); System.in is an InputStream which is typically connected to keyboard input of console programs.
  • 19. DataInputStream Class Java DataInputStream class allows an application to read primitive data (int, float, long etc.)from the input stream in a machine-independent way. Declaration for java.io.DataInputStream class public class DataInputStream extends FilterInputStream implements DataInput Wrap an InputStream in a DataInputStream and then you can read Java primitives via the DataInputStream. That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes. Create a DataInputStream We create a Java DataInputStream via its constructor. Pass an InputStream as parameter from which the primitive data types are to be read
  • 20. DataInputStream dataInputStream = new DataInputStream( new FileInputStream("data/data.bin")); 1.First a DataInputStream is created with a FileInputStream as source for its data. 2. Java primitives are read from the DataInputStream.
  • 21. Java DataInputStream class Methods Method Description int read(byte[] b) It is used to read the number of bytes from the input stream. int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream. int readInt() It is used to read input bytes and return an int value. byte readByte() It is used to read and return the one input byte. char readChar() It is used to read two input bytes and returns a char value.
  • 22. double readDouble() It is used to read eight input bytes and returns a double value. boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero. int skipBytes(int x) It is used to skip over x bytes of data from the input stream. String readUTF() It is used to read a string that has been encoded using the UTF-8 format. void readFully(byte[] b) It is used to read bytes from the input stream and store them into the buffer array.
  • 23. Difference between DataInputStream and BufferedReader • The DataInputStream works with the binary data, while the BufferedReader work with character data. • DataInputStream is a kind of InputStream to read data directly as primitive data types. • BufferedInputStream is a kind of inputStream that reads data from a stream and uses a buffer to optimize speed access to data. • DataInputStream consumes less amount of memory space being it is binary stream, where as BufferedReader consumes more memory space being it is character stream. • The data to be handled is limited in DataInputStream, where as the number of characters to be handled has wide scope in BufferedReader.
  • 24. • All primitive data types can be handled by using the corresponding methods in DataInputStream class, while only string data can be read from BufferedReader class and they need to be parsed into the respective primitives.
  • 25. Scanner Class in Java • The Scanner class is used to get user input, and it is found in the java.util package. • It is used for obtaining the input of the primitive types like int, double, etc. and strings. • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file. A Scanner breaks its input into tokens using a delimiter pattern. • The resulting tokens may then be converted into values of different types using the various next methods. For example, this code allows a user to read a number from System.in: Scanner sc = new Scanner(System.in); • You can declare scanner type object say ‘sc’ • The Scanner class constructor, which takes an InputStream object (i.e., System.in) as a parameter. The System.in specifies the standard console keyboard input.
  • 26. Input Types Method Description nextBoolean() Reads a boolean value from the user nextByte() Reads a byte value from the user nextDouble() Reads a double value from the user nextFloat() Reads a float value from the user nextInt() Reads a int value from the user nextLine() Reads a String value from the user nextLong() Reads a long value from the user nextShort() Reads a short value from the user
  • 27. Difference between Scanner and BufferedReader • Scanner class can be used for user input by importing from java.util package. • BufferedReader class can be used by importing from java.io package. • Buffered Reader reads the input and buffers it. • It hasn’t multiple functions like reading integer or character or long. • Buffered reader just reads a line. • Scanner on the other hand is formatted input. • It has ability to read character, integer, long, etc. • It reads the input and processes it accordingly. • Scanner class uses regular expression in parsing the strings, by default, white space gets set as a delimiter, but you can set any other delimiter. • Scanner is slower than BufferedReader
  • 28. FileInputStream Class • The FileInputStream class of the java.io package can be used to read contents of a file as a stream of bytes. • The Java FileInputStream class is a subclass of Java InputStream. • To read the contents from the file, first make an object of FileInputStream class and specify the file name as an argument to the constructor: 1. Using the path to file FileInputStream input = new FileInputStream(StringPath); 2. Using an object of the file FileInputStream input = new FileInputStream(File fileObject);
  • 29. Methods of FileInputStream • read() - reads a single byte from the file • read(byte[] array) - reads the bytes from the file and stores in the specified array • read(byte[] array, int start, int length) - reads the number of bytes equal to length from the file and stores in the specified array starting from the position start • available()-To get the number of available bytes, we can use the available() method.
  • 30. Convert FileInputStream to Reader • The Java FileInputStream is a byte based stream of data. • We can convert a Java FileInputStream to a Java Reader using the Java InputStreamReader. • The Java InputStreamReader class is thus a subclass of the Java Reader class. • InputStreamReader class, wraps a Java InputStream, thereby turning the byte based InputStream into a character based Reader. • The Java InputStreamReader is often used to read characters from file Example InputStream inputStream = new FileInputStream("c:datainput.txt"); Reader inputStreamReader = new InputStreamReader(inputStream); First creates a FileInputStream and then wraps it in an InputStreamReader. Second, the
  • 31. FileOutputStream in Java • The FileOutputStream class of the java.io package can be used to write data (in bytes) to the files. In order to create a file output stream, we must import the java.io.FileOutputStream package first. we can create a file output stream in Java • 1. Using the path to file FileOutputStream output = new FileOutputStream(String path); • 2. Using an object of the file FileOutputStream output = new FileOutputStream(File fileObject);
  • 32. Methods of FileOutputStream • write() - writes the single byte to the file output stream • write(byte[] array) - writes the bytes from the specified array to the output stream • write(byte[] array, int start, int length) - writes the number of bytes equal to length to the output stream from an array starting from the position start • getBytes() -converts a string into an array of bytes. • flush() -To clear the output stream, we can use the flush() method. This method forces the output stream to write all data to the destination. • close()-It is used to closes the file output stream.