SlideShare a Scribd company logo
1 of 32
CORE JAVA
CHP 5. JAVA INPUT-OUTPUT
MR. JAYANT. P. DALVI
STREAM
• Java I/O (Input and Output) is used to process the input and produce
the output.
• Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and output
operations.
• We can perform file handling in Java by Java I/O API.
STREAM
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a
stream of water that continues to flow.
• In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
• Let's see the code to print output and an error message to the console.
• System.out.println("simple message");
• System.err.println("error message");
• Let's see the code to get input from console.
• int i=System.in.read();//returns ASCII code of 1st character
• System.out.println((char)i);//will print the character
TYPES OF STREAM
• OutputStream
• Java application uses an output
stream to write data to a
destination; it may be a file, an
array, peripheral device or
socket.
• InputStream
• Java application uses an input
stream to read data from a
source; it may be a file, an array,
peripheral device or socket.
InputStream class
• InputStream class is an abstract class. It is the
superclass of all classes representing an input stream
of bytes.
• Useful methods of InputStream
1) public abstract int read()throws IOException-reads
the next byte of data from the input stream. It returns -1
at the end of the file.
2) public int available()throws IOException- returns an
estimate of the number of bytes that can be read from
the current input stream.
3) public void close()throws IOException- is used to
close the current input stream.
OutputStream class
• OutputStream class is an abstract class. It is the
superclass of all classes representing an output
stream of bytes. An output stream accepts output
bytes and sends them to some sink.
• Useful methods of OutputStream
1) public void write(int)throws IOException- is used to
write a byte to the current output stream.
2) public void write(byte[])throws IOException- is used
to write an array of byte to the current output stream.
3) public void flush()throws IOException- flushes the
current output stream.
4) public void close()throws IOException- is used to
close the current output stream.
FileInputStream Class
• Java FileInputStream class obtains input bytes from a
file. It is used for reading byte-oriented data (streams
of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading
streams of characters, it is recommended to use
FileReader class.
• Java FileInputStream class declaration
• Let's see the declaration for java.io.FileInputStream
class:
public class FileInputStream extends InputStream
1. methods :
• int available()-It is used to return the
estimated number of bytes that can be read
from the input stream.
• int read()- It is used to read the byte of data
from the input stream.
• int read(byte[] b)- It is used to read up to
b.length bytes of data from the input stream.
• int read(byte[] b, int off, int len)- It is used to
read up to len bytes of data from the input
stream.
• void close()-It is used to closes the stream.
program of reading single character
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String[] args) {
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Java FileInputStream example 2: read all
charactersimport java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Java FileOutputStream Class
• Java FileOutputStream is an output stream used for
writing data to a file.
• If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented
as well as character-oriented data through
FileOutputStream class. But, for character-oriented
data, it is preferred to use FileWriter than
FileOutputStream.
• FileOutputStream class declaration
• Let's see the declaration for
Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream
• FileOutputStream class methods
• protected void finalize()- It is used to clean up the
connection with the file output stream.
• void write(byte[] ary) - It is used to write
ary.length bytes from the byte array to the file output
stream.
• void write(byte[] ary, int off, int len)- It is used to write
len bytes from the byte array starting at offset off to the
file output stream.
• void write(int b)- It is used to write the specified byte to
the file output stream.
• void close()- It is used to closes the file output stream.
Java FileOutputStream Example 1: write byte
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java FileOutputStream example 2: write string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java Reader Class
• Java Reader is an abstract class for reading character streams. The only methods that a subclass
must implement are read(char[], int, int) and close().
• Constructor:
• protected Reader()- It creates a new character-stream reader whose critical sections will
synchronize on the reader itself.
• Methods:
• abstract void close()-It closes the stream and releases any system resources associated with it.
• int read()- It reads a single character.
• int read(char[] cbuf)- It reads characters into an array.
• abstract int read(char[] cbuf, int off, int len)- It reads characters into a portion of an array.
• int read(CharBuffer target)-It attempts to read characters into the specified character buffer.
Reader class
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("D:testout.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Java Writer
• It is an abstract class for writing to character streams. The methods
that a subclass must implement are write(char[], int, int), flush(), and
close().
• Constructor
• protected Writer()- It creates a new character-stream writer whose
critical sections will synchronize on the writer itself.
Writer class
• Methods:
• Writer append(char c)- It appends the specified character to this writer.
• Writer append(CharSequence csq)- It appends the specified character sequence to this writer
• Writer append(CharSequence csq, int start, int end)- It appends a subsequence of the specified character
sequence to this writer.
• abstract void close()- It closes the stream, flushing it first.
• abstract void flush()-It flushes the stream.
• void write(char[] cbuf) -It writes an array of characters.
• abstract void write(char[] cbuf, int off, int len)-It writes a portion of an array of characters.
• void write(int c)-It writes a single character.
• void write(String str)-it writes a string.
• void write(String str, int off, int len) -It writes a portion of a string.
writer example
import java.io.*;
public class WriterExample1 {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java FileReader Class
• Java FileReader class is used to read data from the file. It returns data
in byte format like FileInputStream class.
• It is character-oriented class which is used for file handling in java.
• Methods of FileReader class:
• int read()- It is used to return a character in ASCII form. It returns -1 at
the end of file.
• void close()-It is used to close the FileReader class.
FILEREADER CLASS EXAMPLE
package com.javatpoint;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Java FileWriter Class
• Java FileWriter class is used to write character-oriented data to a file. It is character-
oriented class which is used for file handling in java.
• Unlike FileOutputStream class, you don't need to convert string into byte array because it
provides method to write string directly.
• Methods of FileWriter class
• void write(String text) - It is used to write the string into FileWriter.
• void write(char c)- It is used to write the char into FileWriter.
• void write(char[] c)- It is used to write char array into FileWriter.
• void flush()- It is used to flushes the data of FileWriter.
• void close()- It is used to close the FileWriter.
FILEWRITER CLASS EXAMPLE
package com.javatpoint;
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Java BufferedInputStream Class
• Java BufferedInputStream class is used to read information from stream. It
internally uses buffer mechanism to make the performance fast.
• The important points about BufferedInputStream are:
• When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
• When a BufferedInputStream is created, an internal buffer array is created.
Java BufferedInputStream class methods
• int available()- It returns an estimate number of bytes that can be
read from the input stream without blocking by the next invocation
method for the input stream.
• int read()- It read the next byte of data from the input stream.
• int read(byte[] b, int off, int ln)- It read the bytes from the specified
byte-input stream into a specified byte array, starting with the given
offset.
• void close()-It closes the input stream and releases any of the system
resources associated with the stream.
BUFFEREDINPUTSTREAM CLASS
package com.javatpoint;
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Java BufferedOutputStream Class
• Java BufferedOutputStream class is used for buffering an output
stream. It internally uses buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the
performance fast.
• For adding the buffer in an OutputStream, use the
BufferedOutputStream class.
Java BufferedOutputStream class methods
• void write(int b)-It writes the specified byte to the buffered output
stream.
• void write(byte[] b, int off, int len)- It write the bytes from the
specified byte-input stream into a specified byte array, starting with
the given offset
• void flush()- It flushes the buffered output stream.
EXAMPLE
• In this example, we are writing
the textual information in the
BufferedOutputStream object
which is connected to the
FileOutputStream object. The
flush() flushes the data of one
stream and send it into another.
It is required if you have
connected the one stream with
another.
package com.javatpoint;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new
FileOutputStream("D:testout.txt");
BufferedOutputStream bout=new
BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Java BufferedReader Class
• Java BufferedReader class is
used to read the text from a
character-based input stream. It
can be used to read data line by
line by readLine() method. It
makes the performance fast. It
inherits Reader class.
• Java BufferedReader class methods
• int read()- It is used for reading a
single character.
• int read(char[] cbuf, int off, int len)-
It is used for reading characters
into a portion of an array.
• void close()- It closes the input
stream and releases any of the
system resources associated with
the stream.
EXAMPLE
package com.javatpoint;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Java BufferedWriter Class
• Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.
• Class methods
• void newLine() It is used to add a new line by writing a line separator.
• void write(int c)-It is used to write a single character.
• void write(char[] cbuf, int off, int len)-It is used to write a portion of an array of characters.
• void write(String s, int off, int len)-It is used to write a portion of a string.
• void flush()-It is used to flushes the input stream.
• void close()- It is used to closes the input stream
EXAMPLE
package com.javatpoint;
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}
Java - ObjectStreamClass • ObjectStreamClass act as a
Serialization descriptor for class.
This class contains the name and
serialVersionUID of the class.

More Related Content

What's hot (20)

C programming - String
C programming - StringC programming - String
C programming - String
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Python programming
Python programmingPython programming
Python programming
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
 
Interface
InterfaceInterface
Interface
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Exception handling
Exception handling Exception handling
Exception handling
 

Similar to Java I/O (20)

Java Day-6
Java Day-6Java Day-6
Java Day-6
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Files io
Files ioFiles io
Files io
 
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
 
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
 
Java
JavaJava
Java
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
JAVA
JAVAJAVA
JAVA
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 

More from Jayant Dalvi

Linux System Administration
Linux System AdministrationLinux System Administration
Linux System AdministrationJayant Dalvi
 
Linux System Administration
Linux System AdministrationLinux System Administration
Linux System AdministrationJayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design Jayant Dalvi
 
Information system audit 2
Information system audit 2 Information system audit 2
Information system audit 2 Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design Jayant Dalvi
 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkitJayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design Jayant Dalvi
 
Information system audit
Information system audit Information system audit
Information system audit Jayant Dalvi
 
Information system audit
Information system audit Information system audit
Information system audit Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design Jayant Dalvi
 
Information system audit
Information system audit Information system audit
Information system audit Jayant Dalvi
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Object Oriented Programming using C++
Object Oriented Programming using C++Object Oriented Programming using C++
Object Oriented Programming using C++Jayant Dalvi
 

More from Jayant Dalvi (16)

Linux System Administration
Linux System AdministrationLinux System Administration
Linux System Administration
 
Linux System Administration
Linux System AdministrationLinux System Administration
Linux System Administration
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Information system audit 2
Information system audit 2 Information system audit 2
Information system audit 2
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkit
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Information system audit
Information system audit Information system audit
Information system audit
 
Information system audit
Information system audit Information system audit
Information system audit
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Information system audit
Information system audit Information system audit
Information system audit
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Object Oriented Programming using C++
Object Oriented Programming using C++Object Oriented Programming using C++
Object Oriented Programming using C++
 

Recently uploaded

“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
 
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
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
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
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

“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...
 
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
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
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 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🔝
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
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
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
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🔝
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Java I/O

  • 1. CORE JAVA CHP 5. JAVA INPUT-OUTPUT MR. JAYANT. P. DALVI
  • 2. STREAM • Java I/O (Input and Output) is used to process the input and produce the output. • Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. • We can perform file handling in Java by Java I/O API.
  • 3. STREAM • A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. • In Java, 3 streams are created for us automatically. All these streams are attached with the console. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream • Let's see the code to print output and an error message to the console. • System.out.println("simple message"); • System.err.println("error message"); • Let's see the code to get input from console. • int i=System.in.read();//returns ASCII code of 1st character • System.out.println((char)i);//will print the character
  • 4. TYPES OF STREAM • OutputStream • Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket. • InputStream • Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket.
  • 5. InputStream class • InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes. • Useful methods of InputStream 1) public abstract int read()throws IOException-reads the next byte of data from the input stream. It returns -1 at the end of the file. 2) public int available()throws IOException- returns an estimate of the number of bytes that can be read from the current input stream. 3) public void close()throws IOException- is used to close the current input stream.
  • 6. OutputStream class • OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. • Useful methods of OutputStream 1) public void write(int)throws IOException- is used to write a byte to the current output stream. 2) public void write(byte[])throws IOException- is used to write an array of byte to the current output stream. 3) public void flush()throws IOException- flushes the current output stream. 4) public void close()throws IOException- is used to close the current output stream.
  • 7. FileInputStream Class • Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class. • Java FileInputStream class declaration • Let's see the declaration for java.io.FileInputStream class: public class FileInputStream extends InputStream 1. methods : • int available()-It is used to return the estimated number of bytes that can be read from the input stream. • int read()- It is used to read the byte of data from the input stream. • int read(byte[] b)- It is used to read up to b.length bytes of data from the input stream. • int read(byte[] b, int off, int len)- It is used to read up to len bytes of data from the input stream. • void close()-It is used to closes the stream.
  • 8. program of reading single character import java.io.FileInputStream; public class DataStreamExample { public static void main(String[] args) { try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=fin.read(); System.out.print((char)i); fin.close(); }catch(Exception e){System.out.println(e);} } }
  • 9. Java FileInputStream example 2: read all charactersimport java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=0; while((i=fin.read())!=-1){ System.out.print((char)i); } fin.close(); }catch(Exception e){System.out.println(e);} } }
  • 10. Java FileOutputStream Class • Java FileOutputStream is an output stream used for writing data to a file. • If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. • FileOutputStream class declaration • Let's see the declaration for Java.io.FileOutputStream class: public class FileOutputStream extends OutputStream • FileOutputStream class methods • protected void finalize()- It is used to clean up the connection with the file output stream. • void write(byte[] ary) - It is used to write ary.length bytes from the byte array to the file output stream. • void write(byte[] ary, int off, int len)- It is used to write len bytes from the byte array starting at offset off to the file output stream. • void write(int b)- It is used to write the specified byte to the file output stream. • void close()- It is used to closes the file output stream.
  • 11. Java FileOutputStream Example 1: write byte import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); fout.write(65); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } }
  • 12. Java FileOutputStream example 2: write string import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); String s="Welcome to javaTpoint."; byte b[]=s.getBytes();//converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } }
  • 13. Java Reader Class • Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). • Constructor: • protected Reader()- It creates a new character-stream reader whose critical sections will synchronize on the reader itself. • Methods: • abstract void close()-It closes the stream and releases any system resources associated with it. • int read()- It reads a single character. • int read(char[] cbuf)- It reads characters into an array. • abstract int read(char[] cbuf, int off, int len)- It reads characters into a portion of an array. • int read(CharBuffer target)-It attempts to read characters into the specified character buffer.
  • 14. Reader class import java.io.*; public class ReaderExample { public static void main(String[] args) { try { Reader reader = new FileReader("D:testout.txt"); int data = reader.read(); while (data != -1) { System.out.print((char) data); data = reader.read(); } reader.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
  • 15. Java Writer • It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). • Constructor • protected Writer()- It creates a new character-stream writer whose critical sections will synchronize on the writer itself.
  • 16. Writer class • Methods: • Writer append(char c)- It appends the specified character to this writer. • Writer append(CharSequence csq)- It appends the specified character sequence to this writer • Writer append(CharSequence csq, int start, int end)- It appends a subsequence of the specified character sequence to this writer. • abstract void close()- It closes the stream, flushing it first. • abstract void flush()-It flushes the stream. • void write(char[] cbuf) -It writes an array of characters. • abstract void write(char[] cbuf, int off, int len)-It writes a portion of an array of characters. • void write(int c)-It writes a single character. • void write(String str)-it writes a string. • void write(String str, int off, int len) -It writes a portion of a string.
  • 17. writer example import java.io.*; public class WriterExample1 { public static void main(String[] args) { try { Writer w = new FileWriter("output.txt"); String content = "I love my country"; w.write(content); w.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }
  • 18. Java FileReader Class • Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. • It is character-oriented class which is used for file handling in java. • Methods of FileReader class: • int read()- It is used to return a character in ASCII form. It returns -1 at the end of file. • void close()-It is used to close the FileReader class.
  • 19. FILEREADER CLASS EXAMPLE package com.javatpoint; import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:testout.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } }
  • 20. Java FileWriter Class • Java FileWriter class is used to write character-oriented data to a file. It is character- oriented class which is used for file handling in java. • Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly. • Methods of FileWriter class • void write(String text) - It is used to write the string into FileWriter. • void write(char c)- It is used to write the char into FileWriter. • void write(char[] c)- It is used to write char array into FileWriter. • void flush()- It is used to flushes the data of FileWriter. • void close()- It is used to close the FileWriter.
  • 21. FILEWRITER CLASS EXAMPLE package com.javatpoint; import java.io.FileWriter; public class FileWriterExample { public static void main(String args[]){ try{ FileWriter fw=new FileWriter("D:testout.txt"); fw.write("Welcome to javaTpoint."); fw.close(); }catch(Exception e){System.out.println(e);} System.out.println("Success..."); } }
  • 22. Java BufferedInputStream Class • Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast. • The important points about BufferedInputStream are: • When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time. • When a BufferedInputStream is created, an internal buffer array is created.
  • 23. Java BufferedInputStream class methods • int available()- It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream. • int read()- It read the next byte of data from the input stream. • int read(byte[] b, int off, int ln)- It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset. • void close()-It closes the input stream and releases any of the system resources associated with the stream.
  • 24. BUFFEREDINPUTSTREAM CLASS package com.javatpoint; import java.io.*; public class BufferedInputStreamExample{ public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("D:testout.txt"); BufferedInputStream bin=new BufferedInputStream(fin); int i; while((i=bin.read())!=-1){ System.out.print((char)i); } bin.close(); fin.close(); }catch(Exception e){System.out.println(e);} } }
  • 25. Java BufferedOutputStream Class • Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. • For adding the buffer in an OutputStream, use the BufferedOutputStream class.
  • 26. Java BufferedOutputStream class methods • void write(int b)-It writes the specified byte to the buffered output stream. • void write(byte[] b, int off, int len)- It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset • void flush()- It flushes the buffered output stream.
  • 27. EXAMPLE • In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another. package com.javatpoint; import java.io.*; public class BufferedOutputStreamExample{ public static void main(String args[])throws Exception{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); BufferedOutputStream bout=new BufferedOutputStream(fout); String s="Welcome to javaTpoint."; byte b[]=s.getBytes(); bout.write(b); bout.flush(); bout.close(); fout.close(); System.out.println("success"); } }
  • 28. Java BufferedReader Class • Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class. • Java BufferedReader class methods • int read()- It is used for reading a single character. • int read(char[] cbuf, int off, int len)- It is used for reading characters into a portion of an array. • void close()- It closes the input stream and releases any of the system resources associated with the stream.
  • 29. EXAMPLE package com.javatpoint; import java.io.*; public class BufferedReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:testout.txt"); BufferedReader br=new BufferedReader(fr); int i; while((i=br.read())!=-1){ System.out.print((char)i); } br.close(); fr.close(); } }
  • 30. Java BufferedWriter Class • Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings. • Class methods • void newLine() It is used to add a new line by writing a line separator. • void write(int c)-It is used to write a single character. • void write(char[] cbuf, int off, int len)-It is used to write a portion of an array of characters. • void write(String s, int off, int len)-It is used to write a portion of a string. • void flush()-It is used to flushes the input stream. • void close()- It is used to closes the input stream
  • 31. EXAMPLE package com.javatpoint; import java.io.*; public class BufferedWriterExample { public static void main(String[] args) throws Exception { FileWriter writer = new FileWriter("D:testout.txt"); BufferedWriter buffer = new BufferedWriter(writer); buffer.write("Welcome to javaTpoint."); buffer.close(); System.out.println("Success"); } }
  • 32. Java - ObjectStreamClass • ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and serialVersionUID of the class.