Java I - O
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.
How to write a common data to multiple files using single stream only ?
Java I/O
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.
Description
IOException:
output stream.
Java I/O
2) public void write(byte[])throws
IOException:
IOException:
4) public void close()throws
IOException:
stream.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing
an input stream of bytes.
Description
read()throws IOException:
IOException:
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.
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.
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();
}
}
Description
creates a new byte array output stream with the
initial capacity of 32 bytes, though its size
increases if necessary.
ByteArrayOutputStream(int
size)
Java I/O
Methods of ByteArrayOutputStream class
Method
Description
IOException
stream.
IOException
3) public void write(byte[] b) throws
IOException
4) public void flush()
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
Description
1) SequenceInputStream(InputStream
2) SequenceInputStream(Enumeration
e)
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();
}
}
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.
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.
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...
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.
Description
FileWriter(String file)
FileWriter(File file)
Description
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...
Description
FileReader(String
file)
FileReader(File
file)
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()
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.
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:
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
18
Java I/O
Amit
Welcome Amit
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);
Method
1) public String readLine()
Description
is used to read a single line of text from the
console.
fmt,Object... args)
4) public char[]
readPassword(String fmt,Object...
args)
the console.
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
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.
Method
Description
public String
nextLine()
public short
nextShort()
public int nextInt()
public float
nextFloat()
public double
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);
}
}
Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
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.
public void print(char[] c): it prints the specified character array values.
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.
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.
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.
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.
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.
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