0% found this document useful (0 votes)
92 views

Java I - O

Java I/O allows reading input from and writing output to various sources like files, network sockets, and devices. It uses streams to perform efficient I/O operations. The core classes for I/O in Java are InputStream, OutputStream, FileInputStream, and FileOutputStream. ByteArrayOutputStream and SequenceInputStream can be used to write to or read from multiple streams respectively.

Uploaded by

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

Java I - O

Java I/O allows reading input from and writing output to various sources like files, network sockets, and devices. It uses streams to perform efficient I/O operations. The core classes for I/O in Java are InputStream, OutputStream, FileInputStream, and FileOutputStream. ByteArrayOutputStream and SequenceInputStream can be used to write to or read from multiple streams respectively.

Uploaded by

Daksh Mathur
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Java I/O

Java I/O (Input and Output) is used to process the input and produce the output
based on the input.
Java uses the concept of 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 IO API.

Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a
stream because it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached
with 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 error message to the console.
1.
2.

System.out.println("simple message");
System.err.println("error message");
Let's see the code to get input from console.

1.
2.

int i=System.in.read();//returns ASCII code of 1st character


System.out.println((char)i);//will print the character
Questions

How to write a common data to multiple files using single stream only ?

How can we access multiple files by single stream ?

How can we improve the performance of Input and Output operation ?

How many ways can we read data from the keyboard?

What is console class ?

Java I/O

How to compress and uncompress the data of a file?

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.
Let's understand working of Java OutputStream and InputStream by the figure given
below.

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.

Commonly used methods of OutputStream class


Method

Description

1) public void write(int)throws

is used to write a byte to the current

IOException:

output stream.

Java I/O
2) public void write(byte[])throws

is used to write an array of byte to the

IOException:

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.

InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing
an input stream of bytes.

Commonly used methods of InputStream class


Method

Description

1) public abstract int

reads the next byte of data from the input

read()throws IOException:

stream.It returns -1 at the end of file.

2) public int available()throws

returns an estimate of the number of bytes

IOException:

that can be read from the current input


stream.

3) public void close()throws

is used to close the current input stream.

IOException:

Java I/O

Java I/O
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.

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.

Example of Java FileOutputStream class


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
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);}
}
}
Output:success...

Java I/O
Java FileInputStream class
Java FileInputStream class obtains input bytes from a file.It is used for reading
streams of raw bytes such as image data. For reading streams of characters, consider
using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video
etc.

Example of FileInputStream class


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

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:Sachin is my favourite player.

Java I/O
Example of Reading the data of current java file and
writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file,
image file, video file etc. In this example, we are reading the data of C.java file and
writing it into another file M.java.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

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 ByteArrayOutputStream class


Java ByteArrayOutputStream class is used to write data into multiple files. In this
stream, the data is written into a byte array that can be written to multiple stream.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream automatically grows according to data.

Closing the ByteArrayOutputStream has no effect.

Constructors of ByteArrayOutputStream class


Constructor
ByteArrayOutputStream()

Description
creates a new byte array output stream with the
initial capacity of 32 bytes, though its size
increases if necessary.

ByteArrayOutputStream(int

creates a new byte array output stream, with a

size)

buffer capacity of the specified size, in bytes.

Java I/O
Methods of ByteArrayOutputStream class
Method

Description

1) public synchronized void

writes the complete contents of this byte

writeTo(OutputStream out) throws

array output stream to the specified output

IOException

stream.

2) public void write(byte b) throws

writes byte into this stream.

IOException
3) public void write(byte[] b) throws

writes byte array into this stream.

IOException
4) public void flush()

flushes this stream.

5) public void close()

has no affect, it doesn't closes the


bytearrayoutputstream.

Java ByteArrayOutputStream Example


Let's see a simple example of java ByteArrayOutputStream class to write data into 2
files.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

import java.io.*;
class S{
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("f1.txt");
FileOutputStream fout2=new FileOutputStream("f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(139);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("success...");
}
}
success...

Java I/O

Java SequenceInputStream class


Java SequenceInputStream class is used to read data from multiple streams. It reads
data of streams one by one.

Constructors of SequenceInputStream class:


Constructor

Description

1) SequenceInputStream(InputStream

creates a new input stream by

s1, InputStream s2)

reading the data of two input


stream in order, first s1 and then
s2.

2) SequenceInputStream(Enumeration

creates a new input stream by

e)

reading the data of an


enumeration whose type is
InputStream.

Java I/O
Simple example of SequenceInputStream class
In this example, we are printing the data of two files f1.txt and f2.txt.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
int i;
while((i=sis.read())!=-1){
System.out.println((char)i);
}
sis.close();
fin1.close();
fin2.close();
}
}

Example of SequenceInputStream that reads the


data from two files
In this example, we are writing the data of two files f1.txt and f2.txt into another file
named f3.txt.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

//reading data of 2 files and writing it into one file


import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
FileOutputStream fout=new FileOutputStream("f3.txt");
SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
int i;
while((i.sisread())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin.close();
fin.close();
}
}

10

Java I/O
Example of SequenceInputStream class that reads
the data from multiple files using enumeration
If we need to read the data from more than two files, we need to have these
information in the Enumeration object. Enumeration object can be get by calling
elements method of the Vector class. Let's see the simple example where we are
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.

reading the data from the 4 files.


import java.io.*;
import java.util.*;
class B{
public static void main(String args[])throws IOException{
//creating the FileInputStream objects for all the files
FileInputStream fin=new FileInputStream("A.java");
FileInputStream fin2=new FileInputStream("abc2.txt");
FileInputStream fin3=new FileInputStream("abc.txt");
FileInputStream fin4=new FileInputStream("B.java");
//creating Vector object to all the stream
Vector v=new Vector();
v.add(fin);
v.add(fin2);
v.add(fin3);
v.add(fin4);
//creating enumeration object by calling the elements method
Enumeration e=v.elements();
//passing the enumeration object in the constructor
SequenceInputStream bin=new SequenceInputStream(e);
int i=0;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close();
}
}

11

Java I/O
Java BufferedOutputStream and
BufferedInputStream
Java BufferedOutputStream class
Java BufferedOutputStream class uses an internal buffer to store data. It adds more
efficiency than to write data directly into a stream. So, it makes the performance fast.

Example of BufferedOutputStream class:


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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Sachin is my favourite player";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
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.

12

Java I/O
Example of Java BufferedInputStream
Let's see the simple example to read data of file using BufferedInputStream.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.println((char)i);
}
bin.close();
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:
Sachin is my favourite player

13

Java I/O
Java FileWriter and FileReader (File
Handling in java)
Java FileWriter and FileReader classes are used to write and read data from text files.
These are character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if
you have to read and write the textual information.

Java FileWriter class


Java FileWriter class is used to write character-oriented data to the file.

Constructors of FileWriter class


Constructor

Description

FileWriter(String file)

creates a new file. It gets file name in string.

FileWriter(File file)

creates a new file. It gets file name in File object.

Methods of FileWriter class


Method

Description

1) public void write(String text)

writes the string into FileWriter.

2) public void write(char c)

writes the char into FileWriter.

3) public void write(char[] c)

writes char array into FileWriter.

4) public void flush()

flushes the data of FileWriter.

5) public void close()

closes FileWriter.

14

Java I/O
Java FileWriter Example
In this example, we are writing the data in the file abc.txt.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

copy to clipboard
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Output:
success...

Java FileReader class


Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.

Constructors of FileWriter class


Constructor

Description

FileReader(String

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

file)

mode. If file doesn't exist, it throws FileNotFoundException.

FileReader(File

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

file)

mode. If file doesn't exist, it throws FileNotFoundException.

Methods of FileReader class


Method
1) public int read()

Description
returns a character in ASCII form. It returns -1 at the end of
file.

15

Java I/O
2) public void

closes FileReader.

close()

Java FileReader Example


In this example, we are reading the data from the file abc.txt file.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
Output:
my name is sachin

16

Java I/O
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class
implements the Appendable interface. Its buffer automatically grows when data is
written in this stream. Calling the close() method on this object has no effect.

Example of CharArrayWriter class:


In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("my name is");
FileWriter
FileWriter
FileWriter
FileWriter

f1=new
f2=new
f3=new
f4=new

FileWriter("a.txt");
FileWriter("b.txt");
FileWriter("c.txt");
FileWriter("d.txt");

out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
}
}

17

Java I/O
Reading data from keyboard:
There are many ways to read data from the keyboard. For example:

InputStreamReader

Console

Scanner

DataInputStream etc.

InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two
tasks:

connects to input stream of keyboard

converts the byte-oriented stream into character-oriented stream

BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by


InputStreamReader and BufferdReader class:
In this example, we are connecting the BufferedReader stream with the
InputStreamReader stream for reading the line by line data from the keyboard.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

//<b><i>Program of reading data</i></b>


import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter your name

18

Java I/O
Amit
Welcome Amit

Another Example of reading data from keyboard by


InputStreamReader and BufferdReader class until
the user writes stop
In this example, we are reading and printing the data until the user prints stop.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop

19

Java I/O

20

Java I/O
Java Console class
The Java Console class is be used to get input from console. It provides methods to
read text and password.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class
is introduced since 1.5.
Let's see a simple example to read text from console.
1.
2.

String text=System.console().readLine();
System.out.println("Text is: "+text);

Methods of Console class


Let's see the commonly used methods of Console class.

Method
1) public String readLine()

Description
is used to read a single line of text from the
console.

2) public String readLine(String

it provides a formatted prompt then reads

fmt,Object... args)

the single line of text from the console.

3) public char[] readPassword()

is used to read password that is not being


displayed on the console.

4) public char[]

it provides a formatted prompt then reads

readPassword(String fmt,Object...

the password that is not being displayed on

args)

the console.

How to get the object of Console


System class provides a static method console() that returns the unique instance of
Console class.
1.

public static Console console(){}


Let's see the code to get the instance of Console class.

1.

Console c=System.console();

21

Java I/O
Java Console Example
1.
2.
3.
4.
5.
6.
7.
8.
9.

import java.io.*;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output:
Enter your name: james gosling
Welcome james gosling

Java Console Example to read password


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

import java.io.*;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output:
Enter password:
Password is: sonoo

22

Java I/O
Java Scanner class
There are various ways to read input from the keyboard, the java.util.Scanner class is
one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace bydefault. It provides many methods to read and parse various primitive
values.
Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.

Commonly used methods of Scanner class


There is a list of commonly used Scanner class methods:

Method

Description

public String next()

it returns the next token from the scanner.

public String

it moves the scanner position to the next line and returns

nextLine()

the value as a string.

public byte nextByte()

it scans the next token as a byte.

public short

it scans the next token as a short value.

nextShort()
public int nextInt()

it scans the next token as an int value.

public long nextLong()

it scans the next token as a long value.

public float

it scans the next token as a float value.

nextFloat()
public double

it scans the next token as a double value.

nextDouble()

23

Java I/O
Java Scanner Example to get input from console
Let's see the simple example of the Java Scanner class which reads the int, string and
double value as an input:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);

}
}

System.out.println("Enter your rollno");


int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();

Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

Java Scanner Example with delimiter


Let's see the example of Scanner class with delimiter. The \s represents whitespace.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

import java.util.*;
public class ScannerTest2{
public static void main(String args[]){
String input = "10 tea 20 coffee 30 tea buiscuits";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();

24

Java I/O
11.

}}

Output:
10
tea
20
coffee

java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The
PrintStream class automatically flushes the data so there is no need to call flush()
method. Moreover, its methods don't throw IOException.

Commonly used methods of PrintStream class:


There are many methods in PrintStream class. Let's see commonly used methods of
PrintStream class:
public void print(boolean b): it prints the specified boolean value.

public void print(char c): it prints the specified char value.

public void print(char[] c): it prints the specified character array values.

public void print(int i): it prints the specified int value.

public void print(long l): it prints the specified long value.

public void print(float f): it prints the specified float value.

public void print(double d): it prints the specified double value.

public void print(String s): it prints the specified string value.

public void print(Object obj): it prints the specified object value.

public void println(boolean b): it prints the specified boolean value and
terminates the line.

public void println(char c): it prints the specified char value and terminates
the line.

public void println(char[] c): it prints the specified character array values

25

Java I/O
and terminates the line.

public void println(int i): it prints the specified int value and terminates the
line.

public void println(long l): it prints the specified long value and terminates
the line.

public void println(float f): it prints the specified float value and terminates
the line.

public void println(double d): it prints the specified double value and
terminates the line.

public void println(String s): it prints the specified string value and
terminates the line./li>

public void println(Object obj): it prints the specified object value and
terminates the line.

public void println(): it terminates the line only.

public void printf(Object format, Object... args): it writes the formatted


string to the current stream.

public void printf(Locale l, Object format, Object... args): it writes the


formatted string to the current stream.

public void format(Object format, Object... args): it writes the formatted


string to the current stream using specified format.

public void format(Locale l, Object format, Object... args): it writes the


formatted string to the current stream using specified format.

Example of java.io.PrintStream class:


In this example, we are simply printing integer and string values.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("mfile.txt");
PrintStream pout=new PrintStream(fout);
pout.println(1900);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
}

26

Java I/O
14.

Example of printf() method of java.io.PrintStream class:


Let's see the simple example of printing integer value by format specifier.
1.
2.
3.
4.
5.
6.
7.

class PrintStreamTest{
public static void main(String args[]){
int a=10;
System.out.printf("%d",a);//Note, out is the object of PrintStream class
}
}
Output:10

27

Java I/O
Compressing and Uncompressing File
The DeflaterOutputStream and InflaterInputStream classes provide mechanism to
compress and uncompress the data in the deflate compression format.

DeflaterOutputStream class:
The DeflaterOutputStream class is used to compress the data in the deflate
compression format. It provides facility to the other compression filters, such as
GZIPOutputStream.

Example of Compressing file using DeflaterOutputStream


class
In this example, we are reading data of a file and compressing it into another file
using DeflaterOutputStream class. You can compress any file, here we are
compressing the Deflater.java file
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.

import java.io.*;
import java.util.zip.*;
class Compress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("Deflater.java");
FileOutputStream fout=new FileOutputStream("def.txt");
DeflaterOutputStream out=new DeflaterOutputStream(fout);
int i;
while((i=fin.read())!=-1){
out.write((byte)i);
out.flush();
}
fin.close();
out.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}

28

Java I/O
InflaterInputStream class:
The InflaterInputStream class is used to uncompress the file in the deflate
compression format. It provides facility to the other uncompression filters, such as
GZIPInputStream class.

Example of uncompressing file using InflaterInputStream


class
In this example, we are decompressing the compressed file def.txt into D.java .
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.

import java.io.*;
import java.util.zip.*;
class UnCompress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("def.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D.java");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}

29

Java I/O
PipedInputStream and PipedOutputStream
classes
The PipedInputStream and PipedOutputStream classes can be used to read and write
data simultaneously. Both streams are connected with each other using the connect()
method of the PipedOutputStream class.

Example of PipedInputStream and PipedOutputStream


classes using threads
Here, we have created two threads t1 and t2. The t1 thread writes the data using the
PipedOutputStream object and the t2 thread reads the data from that pipe using the
PipedInputStream object. Both the piped stream object are connected with each
other.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

31.

import java.io.*;
class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();
pout.connect(pin);//connecting the streams
//creating one thread t1 which writes the data
Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{
pout.write(i);
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
//creating another thread t2 which reads the data
Thread t2=new Thread(){
public void run(){
try{
for(int i=65;i<=90;i++)
System.out.println(pin.read());
}catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}}

30

You might also like