Java I/O (Input and Output) is used to process the input and produce the output based on the input. To store input data on harddisk instead of temporary memory (RAM) you need file handling.
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. The information can be of any type, i.e., object, characters, images or sounds, etc.
Each of the Java I/O classes is meant to do one job and to be used in combination with other to do complex tasks. Hierarchy of classes of Java.io package is given below:
I/O classes are used to get input from any source of data or to send output to any destination. The source and destination of input and output can be file or even memory. In Java information can be stored, and retrieved using a communication system called streams. A stream is a sequence of data. There are two kinds of streams: byte stream and character stream. For example: name can store in characters, images can be stored in bytes.
Let's see the code to print output and error message to the console:
System.out: standard output stream (write data)
System.out.println("simple message");
System.err: standard error stream
System.err.println("error message");
System.in: standard input stream (read data)
Example 1: Let's see the code to get input a character from console.
class ex1{ public static void main(String[] args) throws Exception { System.out.print("Enter character: "); int i=System.in.read(); //returns ASCII code of 1st character System.out.println("Entered character is: "+ (char)i); //will print the character } } /* Enter character: a Entered character is: a */
The File class is not I/O. It provides just an identifier of files and directories. Creating an instance of the File class does not create a file in the operating system. The object of the File class can be created using the following types of File constructors:
File f1 = new File("file.txt"); // file name in current folder File f1 = new File("d:/folder/file.txt"); // full path File f1 = new File("d:/folder","gk.txt"); // directory path and the filename File f1 = new File("folder","gk.txt"); // folder name and file name.
S.No. | Method | Description |
---|---|---|
boolean exists() | Return true if file already exists. | |
boolean canWrite() | Return true if file is writable. | |
boolean canRead() | Return true if file is readable. | |
boolean isFile() | Return true if reference is a file and false for directories references. | |
boolean isDirectory() | Return true if reference is a directory. | |
String getAbsolutePath() | Return the absolute path to the application. |
Example:
import java.io.File; class file { public static void main(String[] args) { //File f1 = new File("file.txt"); //File f1 = new File("d:/folder/file.txt"); //File f1 = new File("d:/folder","gk.txt"); File f1 = new File("folder","gk.txt"); System.out.println("File name : " + f1.getName()); System.out.println("Path : " + f1.getPath()); System.out.println("Absolute Path : " + f1.getAbsolutePath()); System.out.println(f1.exists() ? "Exists" : "doesnot exist"); System.out.println(f1.canWrite()?"Is writable" : "Is not writable"); System.out.println(f1.canRead() ? "Is readable" :"Is not readable"); System.out.println("File Size : " + f1.length() + " bytes"); } }
Java Stream based I/O builts upon four abstract classes: InputStream, OutputStream, Reader and Writer. An object from which we can read a sequence of bytes is called an input stream. An object from which we can write sequence of byte is called output stream. InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes. All OutputStream functions throws IOException.
S.No. | Method | Description |
---|---|---|
public abstract int read() | reads the next byte of data from the input stream. It returns -1 at the end of file. | |
public int available() | returns an estimate of the number of bytes that can be read from the current input stream. | |
public void close() | It is used to close the current input stream. |
Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket. 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 container. All OutputStream functions throws IOException.
S.No. | Method | Description |
---|---|---|
public void write(int) | It is used to write a byte to the current output stream. | |
public void write(byte[]) | It is used to write an array of byte to the current output stream. | |
public void flush() | It flushes the current output stream. | |
public void close() | It is used to close the current output stream. |
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 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: Write in a file using Java FileOutputStream class
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); } } }
Example: Read from a file using Java FileInputStream class
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.print((char)i); } fin.close(); } catch(Exception e) { System.out.println(e); } } } //Output:Sachin is my favorite player.
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 a java file, text file, image file etc. In this example, we are reading the data of 'file1.java' and writing it into another file 'file2.java'.
import java.io.*; class ReadWrite { public static void main(String args[]) throws Exception { FileInputStream fin=new FileInputStream("file1.txt"); FileOutputStream fout=new FileOutputStream("file2.txt"); int i=0; while((i=fin.read())!=-1) { fout.write((byte)i); } fin.close(); fout.close(); } }
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.
S.No. | 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. |
S.No. | Method | Description |
---|---|---|
public synchronized void writeTo(OutputStream out) | writes the complete contents of this byte array output stream to the specified output stream. | |
public void write(byte b) | writes byte into this stream. | |
public void write(byte[] b) | writes byte array into this stream. | |
public void flush() | flushes this stream. | |
public void close() | has no effect, it doesn't close the bytearrayoutputstream. |
Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files.
import java.io.*; class ByteArray { 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(123); bout.writeTo(fout1); bout.writeTo(fout2); bout.flush(); bout.close();//has no effect System.out.println("success..."); } }
Java SequenceInputStream class is used to read data from multiple streams. It reads data of streams one by one.
S.No. | Constructor | Description |
---|---|---|
SequenceInputStream(InputStream s1, InputStream s2) | Creates a new input stream by reading the data of two input stream in order, first s1 and then s2. | |
SequenceInputStream(Enumeration e) | Creates a new input stream by reading the data of an enumeration whose type is InputStream. |
Simple example of SequenceInputStream class: 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) { 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. //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(); } }
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 this information in the Enumeration object. Enumeration object can be used 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 { //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(); } }