Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

IO Streams in Java

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

IO Streams in Java

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

I/O Streams in JAVA

Dr.K.Kartheeban
I/O
 Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g.
harddisk

 Classes provided by package java.io

 Data is transferred to devices by ‘streams‘

output - stream
Program Device

input - stream
Program Device
CIS 068
Overview of I/O Streams
To bring in information, a program opens a stream on
an information source (a file, memory, a socket) and
reads the information sequentially, as shown in the
following figure.
12/31/24 4
Overview of I/O STREAMS Contd.
Similarly, a program can send information to an
external destination by opening a stream to a
destination and writing the information out
sequentially, as shown in the following figure.
12/31/24 6
Overview of I/O streams Contd..

 The java.io package contains a collection of stream classes


that support algorithms for reading and writing.

 To use these classes, a program needs to import the java.io


package.

 The stream classes are divided into two class hierarchies,


based on the data type (either characters or bytes) on which
they operate

i.e Character Stream Classes
Byte Stream Classes
JAVA distinguishes between 2 types of streams:

Text – streams, containing ‘characters‘


Program I ‘ M A S T R I N G \n Device

•Binary Streams, containing 8 – bit information

Program 01101001 11101101 00000000 Device

CIS 068
Having

 2 types of streams (text / binary) and


 2 directions (input / output)

results in 4 base-classes dealing with I/O:

1. InputStream: byte-input
2. OutputStream: byte-output
3. Reader: text-input
4. Writer: text-output
InputStream vs OutputStream
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
Java application uses an output stream to write data to a destination, it
may be a file, an array, peripheral device or socket.

Let's understand working of Java OutputStream and InputStream by the figure


given below.
Streams
InputStream

OutputStream
binary

Reader

Writer
text

CIS 068
Common Method in InputStream

Method Description

public abstract int read() throws reads the next byte of data from
IOException the input stream. It returns -1 at
the end of file.
public int available() throws returns an estimate of the number
IOException of bytes that can be read from the
current input stream.
public void close() throws IOException is used to close the current input
stream.
Common Method in OutputStream
Method Description

1) public void write(int)throws is used to write a byte to the current


IOException output stream.

2) public void write(byte[])throws is used to write an array of byte to


IOException the current output stream.

3) public void flush()throws flushes the current output stream.


IOException

4) public void close()throws is used to close the current output


IOException stream.
FileInputStream and FileOutputStream
(File Handling)

In Java, FileInputStream and FileOutputStream classes are used to read and


write data in file. In another words, they are used for file handling in java.
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);
}
} }
Note: Before running the code, a text file named as "testout.txt" is required
to be created. In this file, we are having following content:

Kartheeban welcomes you all for java programming.

After executing the above program, you will get a single character from the
file which is 75 (in byte form).

To see the text, you need to convert it into character.

Output:
K
import java.io.*;

class SimpleRead
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.println((char)i);
}
fin.close();
}
catch(Exception e)
{
system.out.println(e);
}
} Output:
} Kartheeban welcomes you all for java programming .
Methods
Method Description
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 It is used to read up to len bytes of data from
len) the input stream.
long skip(long x) It is used to skip over and discards x bytes of
data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel
object associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call
when there is no more reference to the file input
stream.
void close() It is used to closes the stream.
Reading the data of current java file and writing it into
another file
import java.io.*;
class C
{
public static void main(String args[])throws Exception
{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");

int i=0;
while((i=fin.read())!=-1)
{
fout.write((byte)i);
}
fin.close();
} }
Java FileOutputStream class

Java FileOutputStream is an output stream for writing data to a


file.

If you have to write primitive values then use FileOutputStream.

Instead, for character-oriented data, prefer FileWriter.

But you can write byte-oriented as well as character-oriented


data.
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); Output:
} Success...
The content of a text file testout.txt is set with the data A.
} testout.txt
} A
import java.io.*;

class StringTest
{
public static void main(String args[])
{
try
{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s=" Kartheeban welcomes you all for java programming“;

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);
}
}
}
Methods
Method Description
protected void finalize() It is sued 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 It is used to write len bytes from the byte array starting at
len) offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output
stream.

FileChannel getChannel() It is used to return the file channel object associated with
the file output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.

void close() It is used to closes the file output stream.


BufferedInputStream Class
Introduction
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.
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);}
}
} Kartheeban welcomes you all for java programming.
Methods
Method Description
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, It read the bytes from the specified byte-input stream into a
int ln) 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.
void reset() It repositions the stream at a position the mark method was last
called on this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input
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.
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 FileOutputStream("D:\\


IO Package\\testout.txt"));
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=“Dr.KK Welcomes U to java.";

byte b[]=s.getBytes();

bout.write(b);

bout.flush();

bout.close();
fout.close();
System.out.println("success");
}
}
Java ByteArrayInputStream Class
The ByteArrayInputStream is composed of two words: ByteArray and
InputStream.

As the name suggests, it can be used to read byte array as input stream.

Java ByteArrayInputStream class contains an internal buffer which is used


to read byte array as stream.

In this stream, the data is read from a byte array.

The buffer of ByteArrayInputStream automatically grows according to data.


Java ByteArrayInputStream class constructors

Constructor Description

ByteArrayInputStream(byte[] ary) Creates a new byte array input stream


which uses ary as its buffer array.

ByteArrayInputStream(byte[] ary, Creates a new byte array input stream


int offset, int len) which uses ary as its buffer array that
can read up to specified len bytes of data
from an array.
import java.io.*;

public class ReadExample


{
public static void main(String[] args) throws IOException
{
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream

ByteArrayInputStream byt = new ByteArrayInputStream(buf);


int k = 0;

while ((k = byt.read()) != -1)


{
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special character is
: " + ch);
}
}
}
Output:

ASCII value of Character is:35; Special character is: #

ASCII value of Character is:36; Special character is: $

ASCII value of Character is:37; Special character is: %

ASCII value of Character is:38; Special character is: &


Methods
Methods Description

int available() It is used to return the number of remaining bytes that


can be read from the input stream.
int read() It is used to read the next byte of data from the input
stream.
int read(byte[] ary, int off, int It is used to read up to len bytes of data from an array
len) of bytes in the input stream.
boolean markSupported() It is used to test the input stream for mark and reset
method.
long skip(long x) It is used to skip the x bytes of input from the input
stream.
void mark(int readAheadLimit) It is used to set the current marked position in the
stream.
void reset() It is used to reset the buffer of a byte array.
void close() It is used for closing a ByteArrayInputStream.
Java ByteArrayOutputStream class

Java ByteArrayOutputStream class is used to write common


data into multiple files.

In this stream, the data is written into a byte array which can be
written to multiple streams later.
Java ByteArrayOutputStream class
constructors
Constructor Description

ByteArrayOutputStream() Creates a new byte array output stream


with the initial capacity of 32 bytes,
though its size increases if necessary.

ByteArrayOutputStream(int size) Creates a new byte array output stream,


with a buffer capacity of the specified
size, in bytes.
import java.io.*;

public class DataStreamExample


{
public static void main(String args[])throws Exception
{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");

ByteArrayOutputStream bout=new ByteArrayOutputStream();


bout.write(65);

bout.writeTo(fout1);
bout.writeTo(fout2);

bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}
Methods
Method Description

int size() It is used to returns the current size of a buffer.


byte[] toByteArray() It is used to create a newly allocated byte array.
String toString() It is used for converting the content into a
string decoding bytes using a platform default
character set.
String toString(String It is used for converting the content into a
charsetName) string decoding bytes using a specified
charsetName.
void write(int b) It is used for writing the byte specified to the
byte array output stream.
void write(byte[] b, int off, int len) It is used for writing len bytes from specified
byte array starting from the offset off to the
byte array output stream.
void writeTo(OutputStream out) It is used for writing the complete content of a
byte array output stream to the specified output
stream.
void reset() It is used to reset the count field of a byte array
output stream to zero value.
void close() It is used to close the ByteArrayOutputStream.
FileReader Class
The FileReader is a convenience class for reading character files ...
FileReader is meant for reading streams of characters.
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}

}}
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 FileInputStream class, you don't need to convert string into


byte array because it provides method to write string directly.
Constructors of FileWriter class
Constructor Description

FileWriter(String Creates a new file. It gets file name in


file) string.

FileWriter(File file) Creates a new file. It gets file name in


File object.

Method Description

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.


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 java.");

fw.close();

}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
import java.io.*;

class Input1
{
public static void main(String args[]) throws Exception
{
FileInputStream fin1=new FileInputStream("D:\\testin1.txt");
FileInputStream fin2=new FileInputStream("D:\\testin2.txt");

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");


SequenceInputStream sis=new SequenceInputStream(fin1,fin2);

int i;
while((i=sis.read())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin1.close();
fin2.close();
System.out.println("Success..");
}
}

You might also like