Java Input/Output is used for processing input and giving out output. The package java.io contains all the required classes needed for input/output operation. Java uses the term stream for the representation of I/O operation.
Stream
A stream is a sequence of data. A stream supports many data such as primitives, objects, localized characters, objects, etc. Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream, Reader, and Writer.
The two types of stream, we will be looking at are:
- Byte Stream
- Character Stream
Byte stream :
The byte stream classes provide a convenient means for handling byte-oriented I/O. The byte stream classes are topped by InputStream and OutputStream among many other classes.
InputStream:
InputStream is an abstract class that defines Java’s model of streaming byte input. It implements the Closeable interface.
Some of the methods defined by InputStream are:
- int available():
Returns the number of bytes of input currently available for reading. - void close():
Closes the input source. Further read attempts will generate an IOException. - void mark(int numBytes):
Places a mark at the current point in the input stream that will remain valid until numBytes bytes are ready. - int read():
Returns an integer representation of the next available byte of input. –1 is returned when the end of the file is encountered. - int read(byte buffer[], int offset, int numBytes):
Attempts to read up to numBytes bytes into the buffer starting at buffer [ offset ], returning the number of bytes successfully read. –1 is returned when the end of the file is encountered. - void reset():
Resets the input pointer to the previously set mark.
OutputStream:
OutputStream is an abstract class that defines streaming byte output. It implements the Closeable and Flushable interfaces.
Some of the methods defined by OutputStream:
- void close():
Closes the output stream. - void flush():
Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. - void write(byte buffer[]):
Writes a complete array of bytes to an output stream. - void write(int b):
Writes a single byte to an output stream.
FileInputStream:
The File InputStream class creates an InputStream that you can use to read bytes from a file. These streams of raw bytes include image data, audio, video, etc.
FileOutputStream:
FileOutputStream creates an OutputStream that you can use to write bytes to a file.
Character Stream:
These streams are used to perform for a 16-bit Unicode. It provides a convenient means for handling the input and output of characters. At the top of the character stream hierarchies are the Reader and Writer abstract classes.
Reader:
Reader is an abstract class that defines Java’s model for reading character stream. It implements the Closeable(close()) and Readable (read(char[], int, int)) interfaces. All of the methods in this class will throw an IOException on error conditions.
Some of the methods defined by Reader:
- abstract void close():
Closes the input source. - void mark(int numChars):
Places a mark at the current point in the input stream that will remain valid until numChars characters are read. - boolean markSupported():
Returns true if mark()/reset() are supported on this stream. - int read():
Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered. - int read(char buffer[]):
Attempts to read up to buffer. length characters into buffer and returns the actual number of characters that were successfully read. –1 is returned when the end of the file is encountered. - boolean ready()
Returns true if the next input request will not wait. Otherwise, it returns false. - void reset():
Resets the input pointer to the previously set mark.
Writer:
Writer is an abstract class that defines Java’s model for writing character stream. It implementsthe Closeable(close()), Flushable(flush()) and Appendable(char[], int, int) interfaces.
Some of the methods defined by Writer:
- Writer append(char c):
Appends c to the end of the invoking output stream. Returns a reference to the invoking stream. - abstract void close():
Closes the output stream. - abstract void flush():
Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. - void write(int ch):
Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered. Writes a single character to the invoking output stream. - Writer append(CharSequence chars):
Appends chars to the end of the invoking output stream. Returns a reference to the invoking stream.
FileReader:
For the reading purposes present on the file, the FileReader creates a class call Reader. It returns data in byte format like FileInputStream class.
Two commonly used constructor in FileReader are
- FileReader(String filePath)
- FileReader(File fileObj)
Methods used in FileReader:
- int read(): return a character in ASCII form, returns -1 at the end of file.
- void close(): close the FileReader class.
Example: Java program for File I/O.
The following example is to read lines and print these to the standard output stream from a file. The source file must be in the current directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.*; class FileReader { public static void main(String args[]) throws IOException { FileReader fr=new FileReader("fileTest.txt"); int i; while((i=fr.read())!=-1) { System.out.print((char)i); } fr.close(); } } |
We have the following text in “fileTest.txt“:
Welcome to Simple 2 Code
Output:
Welcome to Simple 2 Code
FileWriter:
For the writing purposes present on the file, the FileWriter creates a class call Reader. It returns data in byte format like FileOutputStream class.
Four commonly used constructors in FileWriter are:
- FileWriter(String filePath)
- FileWriter(String filePath, boolean append)
- FileWriter(File fileObj)
- FileWriter(File fileObj, boolean append)
Methods used in FileWriter:
- void write(String text): to write the string into FileWriter.
- void write(char c): to write the char into FileWriter.
- void write(char[] c): to write char array into FileWriter.
- void flush(): to flushes the data of FileWriters.
- void close(): to close the FileWriter.
Example: Java program for File I/O.
The following example is to write lines and print these to the standard output stream from a file. The source file must be in the current directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.io.FileWriter; public class FileWriter { public static void main(String args[]) { try{ FileWriter f = new FileWriter("WriterTest.txt"); f.write("Welcome to Simple2Code."); f.close(); }catch(Exception e){ System.out.println(e); } System.out.println("Done"); } } |
Output:
Done
Now check the text file, “WriterTest.txt” in the same directory.
Welcome to Simple2Code.
Example: Use of BufferReader in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.*; class FileReaderBuffer { public static void main(String args[]) throws IOException { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); } } |