IO Stream

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

Java

IO Stream
Java I/O

 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
Stream (Contd…)

 the code to print output and an error message to the


console.
1. System.out.println("simple message");
2. System.err.println("error message");

 the code to get input from console.


1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
OutputStream vs InputStream

 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.
OutputStream vs InputStream
(Contd…)
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
Method Description
1) public void write(int)throws is used to write a byte to the
IOException current output stream.
2) public void is used to write an array of byte
write(byte[])throws IOException to the current output stream.
3) public void flush()throws flushes the current output
IOException stream.
4) public void close()throws is used to close the current
IOException output stream.
OutputStream Hierarchy
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
Method Description

reads the next byte of data


1) public abstract int
from the input stream. It returns
read()throws IOException
-1 at the end of the file.
returns an estimate of the
2) public int available()throws number of bytes that can be
IOException read from the current input
stream.
3) public void close()throws is used to close the current
IOException input stream.
InputStream Hierarchy
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

1. public class FileOutputStream extends OutputStream


2. FileOutputStream class methods
Method Description
protected void It is used to clean up the connection with the file output
finalize() stream.
It is used to write ary.length bytes from the byte array to
void write(byte[] ary)
the file output stream.
void write(byte[] ary, It is used to write len bytes from the byte array starting at
int off, int len) offset off to the file output stream.
It is used to write the specified byte to the file output
void write(int b)
stream.
FileChannel It is used to return the file channel object associated with
getChannel() the file output stream.
It is used to return the file descriptor associated with the
FileDescriptor getFD()
stream.
Java FileOutputStream Example 1: write byte

1.import java.io.FileOutputStream;
2.public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\
testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11.}

Output:

success…
Java FileOutputStream example 2: write string

1.import java.io.FileOutputStream;
2.public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. String s="Welcome to Class.";
7. byte b[]=s.getBytes();//converting string into byte array
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){System.out.println(e);}
12. }
13.}

Output:

success…
Java 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


 public class FileInputStream extends InputStream
Java FileInputStream class methods
Method Description
It is used to return the estimated number of bytes that can be read
int available()
from the input stream.

int read() It is used to read the byte of data from the input stream.
It is used to read up to b.length bytes of data from the input
int read(byte[] b)
stream.
int read(byte[] b, int
It is used to read up to len bytes of data from the input stream.
off, int len)
It is used to skip over and discards x bytes of data from the input
long skip(long x)
stream.
FileChannel It is used to return the unique FileChannel object associated with
getChannel() the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void It is used to ensure that the close method is call when there is no
finalize() more reference to the file input stream.
void close() It is used to closes the stream.
Java FileInputStream example 1: read single character

1.import java.io.FileInputStream;
2.public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }

Output:
W
Java FileInputStream example 2: read all
characters
1.import java.io.FileInputStream;
2.public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=0;
7. while((i=fin.read())!=-1){
8. System.out.print((char)i);
9. }
10. fin.close();
11. }catch(Exception e){System.out.println(e);}
12. }
13. }

Output:
Welcome to Class
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. Let's see the syntax for adding the
buffer in an OutputStream:

 OutputStream os= new BufferedOutputStream(new FileOutputStrea


m("D:\\IO Package\\testout.txt"));
Java BufferedOutputStream Class
(Contd…)
 Java BufferedOutputStream class declaration
 public class BufferedOutputStream extends FilterOutputStream
 Java BufferedOutputStream class constructors
Constructor Description

It creates the new buffered


BufferedOutputStream(OutputSt output stream which is used for
ream os) writing the data to the specified
output stream.
It creates the new buffered
output stream which is used for
BufferedOutputStream(OutputSt
writing the data to the specified
ream os, int size)
output stream with a specified
buffer size.
Java BufferedOutputStream Class
(Contd…)
 Java BufferedOutputStream class methods

Method Description

It writes the specified byte to the


void write(int b)
buffered output stream.
It write the bytes from the specified
void write(byte[] b, int
byte-input stream into a specified byte
off, int len)
array, starting with the given offset
void flush() It flushes the buffered output stream.
Example of BufferedOutputStream class:

1.import java.io.*;
2.public class BufferedOutputStreamExample{
3.public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Welcome to Class.";
7. byte b[]=s.getBytes();
8. bout.write(b);
9. bout.flush();
10. bout.close();
11. fout.close();
12. System.out.println("success");
13.}
14.}

Output:

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 declaration
 public class BufferedInputStream extends FilterInputStream
Java BufferedInputStream Class
(Contd…)
 Java BufferedInputStream class constructors

Constructor Description
It creates the BufferedInputStream
BufferedInputStream(InputStream
and saves it argument, the input
IS)
stream IS, for later use.
It creates the BufferedInputStream
BufferedInputStream(InputStream with a specified buffer size and
IS, int size) saves it argument, the input stream
IS, for later use.
Java BufferedInputStream Class
(Contd…)
 Java BufferedInputStream class methods
Method Description
It returns an estimate number of bytes that can be read from
int available() 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 It read the bytes from the specified byte-input stream into a
off, int ln) specified byte array, starting with the given offset.
It closes the input stream and releases any of the system
void close()
resources associated with the stream.
It repositions the stream at a position the mark method was last
void reset()
called on this input stream.
void mark(int It sees the general contract of the mark method for the input
readlimit) stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean It tests for the input stream to support the mark and reset
markSupported() methods.
Example of Java
BufferedInputStream
1.import java.io.*;
2.public class BufferedInputStreamExample{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.print((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15.}
Output:
Welcome to Class
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(). Most subclasses will override some of the methods defined
here to provide higher efficiency, functionality or both.
 Fields

Modifier and Type Field Description


The object used to
synchronize
protected Object lock
operations on this
stream.
Java Writer (Contd…)

 Constructor

Modifier Constructor Description


It creates a new character-stream writer whose
protected Writer() critical sections will synchronize on the writer
itself.

It creates a new character-stream writer whose


Writer(Object
protected critical sections will synchronize on the
lock)
given object.
Java Writer (Contd…)

 Methods Modifier and Method Description


Type
It appends the specified character to this
Writer append(char c)
writer.
It appends the specified character
Writer append(CharSequence csq)
sequence to this writer
It appends a subsequence of the
append(CharSequence csq,
Writer specified character sequence to this
int start, int end)
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.
write(char[] cbuf, int off, int It writes a portion of an array of
abstract void
len) characters.
void write(int c) It writes a single character.
void write(String str) It writes a string.
write(String str, int off, int
Java Writer Example
Java Writer Example
1.import java.io.*;
2.public class WriterExample {
3. public static void main(String[] args) {
4. try {
5. Writer w = new FileWriter("output.txt");
6. String content = "I love my country";
7. w.write(content);
8. w.close();
9. System.out.println("Done");
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. } Output: output.txt:
14.}
Done I love my country
Java Reader

 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(). Most subclasses, however, will override some of the methods to
provide higher efficiency, additional functionality, or both.
 Some of the implementation class are BufferedReader, CharArrayReader,
FilterReader, InputStreamReader, PipedReader, StringReader
 Fields

Modifier and Type Field Description

The object used to


synchronize
protected Object lock
operations on this
stream
Java Reader (Contd…)

 Constructor

Modifier Constructor Description


It creates a new character-stream reader whose
protected Reader() critical sections will synchronize on the reader
itself.

It creates a new character-stream reader whose


Reader(Objec
protected critical sections will synchronize on the given
t lock)
object.
Java Reader (Contd…)

 Methods Modifier Method Description


and Type
abstract It closes the stream and releases any system resources
close()
void associated with it.
mark(int
void It marks the present position in the stream.
readAheadLimit)
It tells whether this stream supports the mark()
boolean markSupported()
operation.
int read() It reads a single character.
int read(char[] cbuf) It reads characters into an array.
read(char[] cbuf,
abstract int It reads characters into a portion of an array.
int off, int len)
read(CharBuffer It attempts to read characters into the specified
int
target) character buffer.

boolean ready() It tells whether this stream is ready to be read.


void reset() It resets the stream.
long skip(long n) It skips characters.
Java Reader Example
1.import java.io.*;
2.public class ReaderExample {
3. public static void main(String[] args) {
4. try {
5. Reader reader = new FileReader("file.txt");
6. int data = reader.read();
7. while (data != -1) {
8. System.out.print((char) data);
9. data = reader.read();
10. }
11. reader.close();
12. } catch (Exception ex) {
13. System.out.println(ex.getMessage());
14. }
15. }
16.} Output: file.txt:

I love my country I love my country


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.
 Java FileWriter class declaration
 public class FileWriter extends OutputStreamWriter
 Constructors of FileWriter class
Constructor Description

Creates a new file. It gets file


FileWriter(String file)
name in string.
Creates a new file. It gets file
FileWriter(File file)
name in File object.
Java FileWriter Class (Contd…)

 Methods of FileWriter class

Method Description

It is used to write the string into


void write(String text)
FileWriter.
It is used to write the char into
void write(char c)
FileWriter.
It is used to write char array into
void write(char[] c)
FileWriter.
It is used to flushes the data of
void flush()
FileWriter.
void close() It is used to close the FileWriter.
Java FileWriter Example
1.import java.io.FileWriter;
2.public class FileWriterExample {
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("D:\\
testout.txt");
6. fw.write("Welcome to Class.");
7. fw.close();
8. }catch(Exception e)
{System.out.println(e);}
9. System.out.println("Success...");
10. }
Output: testout.txt:
11.}

Success… Welcome to Class.


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.
 Java FileReader class declaration
1. public class FileReader extends InputStreamReader
 Constructors of FileReader class

Constructor Description

It gets filename in string. It opens the given file in read


FileReader(String
mode. If file doesn't exist, it throws
file)
FileNotFoundException.
It gets filename in file instance. It opens the given file in
FileReader(File file) read mode. If file doesn't exist, it throws
FileNotFoundException.
Java FileReader Class (Contd…)

 Methods of FileReader class

thod Description

It is used to return a character in


int read() ASCII form. It returns -1 at the
end of file.
It is used to close the FileReader
void close()
class.
Java FileReader Example
1.import java.io.FileReader;
2.public class FileReaderExample {
3. public static void main(String args[])throws Exception{

4. FileReader fr=new FileReader("D:\\testout.txt");


5. int i;
6. while((i=fr.read())!=-1)
7. System.out.print((char)i);
8. fr.close();
9. }
10.}

Output:

Welcome to Class.
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 declaration
 public class BufferedWriter extends Writer
 Class constructors

Constructor Description

It is used to create a buffered character output


BufferedWriter(Writer
stream that uses the default size for an output
wrt)
buffer.
It is used to create a buffered character output
BufferedWriter(Writer
stream that uses the specified size for an output
wrt, int size)
buffer.
Java BufferedWriter Class (Contd…)

 Class methods

Method Description
It is used to add a new line by writing a
void newLine()
line separator.

void write(int c) It is used to write a single character.

It is used to write a portion of an array of


void write(char[] cbuf, int off, int len)
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 of Java BufferedWriter

1.import java.io.*;
2.public class BufferedWriterExample {
3.public static void main(String[] args) throws Exception {
4. FileWriter writer = new FileWriter("D:\\testout.txt");
5. BufferedWriter buffer = new BufferedWriter(writer);
6. buffer.write("Welcome to Class.");
7. buffer.close();
8. System.out.println("Success");
9. }
10.}
Output: testout.txt:
Success
Welcome to Class.
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 declaration
1. public class BufferedReader extends Reader
 Java BufferedReader class constructors
Constructor Description

It is used to create a buffered


character input stream that uses
BufferedReader(Reader rd)
the default size for an input
buffer.
It is used to create a buffered
BufferedReader(Reader rd, int character input stream that uses
size) the specified size for an input
buffer.
Java BufferedReader Class (Contd…)

 Java BufferedReader class methods


Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int
It is used for reading characters into a portion of an array.
off, int len)
boolean It is used to test the input stream support for the mark and
markSupported() reset method.
String readLine() It is used for reading a line of text.
It is used to test whether the input stream is ready to be
boolean ready()
read.
long skip(long n) It is used for skipping the characters.
It repositions the stream at a position the mark method was
void reset()
last called on this input stream.
void mark(int
It is used for marking the present position in a stream.
readAheadLimit)
It closes the input stream and releases any of the system
void close()
resources associated with the stream.

You might also like