Java Input and Output
Java Input and Output
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.
Stream
In java, 3 streams are created for us automatically. All these streams are
attached with console.
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
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.
1
OutputStream class
Method Description
1) public void write(int)throws is used to write a byte to the current output
IOException: stream.
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 stream.
IOException:
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 that
IOException: can be read from the current input stream.
3) public void close()throws is used to close the current input stream.
IOException:
2
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...");
3
}catch(Exception e){system.out.println(e);}
} }
Output: success...
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);}
}
4
}
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.
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();
}
}
5
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.
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 creates a new byte array output stream, with a
size) buffer capacity of the specified size, in bytes.
Method Description
1) public synchronized void writes the complete contents of this byte
writeTo(OutputStream out) throws array output stream to the specified
IOException output 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.
6
Java ByteArrayOutputStream Example
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...
7
Java SequenceInputStream class
Java SequenceInputStream class is used to read data from multiple streams. It
reads data of streams one by one.
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 e) creates a new input stream by
reading the data of an
enumeration whose type is
InputStream.
In this example, we are printing the data of two files f1.txt and f2.txt.
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)
{
8
System.out.println((char)i);
}
sis.close();
fin1.close();
fin2.close();
}
}
In this example, we are writing the data of two files f1.txt and f2.txt into
another file named f3.txt.
//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);
9
int i;
while((i.sisread())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin.close();
fin.close();
}
}
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 reading the data from the 4 files.
import java.io.*;
import java.util.*;
class B
{
public static void main(String args[])throws IOException
{
10
//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);
11
}
bin.close();
fin.close();
fin2.close();
}
}
12
Java BufferedOutputStream and
BufferedInputStream
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");
13
}
}
Output:
success...
Let's see the simple example to read data of file using BufferedInputStream.
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();
14
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:
15
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.
Constructor Description
FileWriter(File file) creates a new file. It gets file name in File object.
Method Description
1. import java.io.*;
16
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.close();
8. }catch(Exception e){System.out.println(e);}
9. System.out.println("success");
10. }
11. }
Output:
success...
Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.
Constructor Description
Method Description
2) public void
closes FileReader.
close()
In this example, we are reading the data from the file abc.txt file.
1. import java.io.*;
17
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("abc.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.println((char)i);
8.
9. fr.close();
10. }
11. }
Output:
my name is sachin
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.
In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and
d.txt.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("my name is");
7.
8. FileWriter f1=new FileWriter("a.txt");
9. FileWriter f2=new FileWriter("b.txt");
10. FileWriter f3=new FileWriter("c.txt");
11. FileWriter f4=new FileWriter("d.txt");
12.
13. out.writeTo(f1);
14. out.writeTo(f2);
15. out.writeTo(f3);
16. out.writeTo(f4);
17.
18.
18
19. f1.close();
20. f2.close();
21. f3.close();
22. f4.close();
23. }
24. }
InputStreamReader
Console
Scanner
DataInputStream etc.
InputStreamReader class:
BufferedReader class:
1. //<b><i>Program of reading data</i></b>
2.
3. import java.io.*;
4. class G5{
5. public static void main(String args[])throws Exception{
6.
7. InputStreamReader r=new InputStreamReader(System.in);
8. BufferedReader br=new BufferedReader(r);
9.
19
10. System.out.println("Enter your name");
11. String name=br.readLine();
12. System.out.println("Welcome "+name);
13. }
14. }
In this example, we are reading and printing the data until the user prints
stop.
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. String name="";
9.
10. while(name.equals("stop")){
11. System.out.println("Enter data: ");
12. name=br.readLine();
13. System.out.println("data is: "+name);
14. }
15.
16. br.close();
17. r.close();
18. }
19. }
20
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.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
Method Description
System class provides a static method console() that returns the unique
instance of Console class.
1. public static Console console(){}
1. Console c=System.console();
21
Java Console Example
1. import java.io.*;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output:
1. import java.io.*;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output:
Enter password:
Password is: sonoo
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.
There are many methods in PrintStream class. Let's see commonly used
methods of PrintStream class:
22
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 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.
23
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("mfile.txt");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(1900);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12.
13. }
14. }
Let's see the simple example of printing integer value by format specifier.
1. class PrintStreamTest{
2. public static void main(String args[]){
3. int a=10;
4. System.out.printf("%d",a);//Note, out is the object of PrintStream class
5.
6. }
7. }
Output:10
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.
24
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. import java.io.*;
2. class PipedWR{
3. public static void main(String args[])throws Exception{
4. final PipedOutputStream pout=new PipedOutputStream();
5. final PipedInputStream pin=new PipedInputStream();
6.
7. pout.connect(pin);//connecting the streams
8. //creating one thread t1 which writes the data
9. Thread t1=new Thread(){
10. public void run(){
11. for(int i=65;i<=90;i++){
12. try{
13. pout.write(i);
14. Thread.sleep(1000);
15. }catch(Exception e){}
16. }
17. }
18. };
19. //creating another thread t2 which reads the data
20. Thread t2=new Thread(){
21. public void run(){
22. try{
23. for(int i=65;i<=90;i++)
24. System.out.println(pin.read());
25. }catch(Exception e){}
26. }
27. };
28. //starting both threads
29. t1.start();
30. t2.start();
31. }}
25