File Handling using Input-Output Streams in Java
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, disk files, devices, other programs, etc. Streams support many different kinds of data simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. Data is transferred to devices by streams.
Reading/Writing to Stream
A stream is a sequence of data. A program uses an input stream to read data from a source :

A program uses an output stream to write data to a destination:

Types of Streams
- Byte Streams
- Character Streams
- Buffered Streams
JAVA distinguishes between 2 types of streams:
Text – streams, containing ‘characters‘
![]()
Binary Streams, containing 8 – bit information
![]()
1. Byte Streams
Programs use byte streams to perform input and output of 8-bit bytes. Root Classes for Byte Streams are
- InputStream
- OutputStream (both are abstract)
There are many byte stream classes for example FileInputStream and FileOutputStream. Following example shows how to use these classes to copy file.
Example to copy a file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes { public static void main(String[] args) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(“myfile.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
} finally {
if (in != null) {
in.close();
}
if (out != null)
{ out.close(); }
}} }
Important Methods
- int read() : Reads a byte of data from this input stream
- int read(byte[] b) : Reads up to b.length bytes of data from this input stream into an array of bytes
- void write (int b) : Writes the specified byte to this file output stream.
- void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream.
- void close() : Closes the file input and output streams and releases any system resources associated with the stream
2. Character Streams
The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set. Root Classes for Character Streams
- Reader Class
- Writer Class (both are abstract)
Character streams are often “wrappers” for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
Copy Characters Example
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader(“myfile.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1)
{ outputStream.write(c); }
} finally {
if (inputStream != null)
{ inputStream.close();
} if (outputStream != null)
{ outputStream.close();
} } } }
Input and Output Streams
Can read from these streams. Root classes of all input streams:
- The InputStream Class
- The Reader Class
Output or sink (destination) streams. Can write to these streams. Root classes of all output streams:
- The OutputStream Class
- The Writer Class
Control Flow of an I/O operation
- Create a stream object and associate it with a datasource (data-destination)
- Give the stream object the desired functionality through stream chaining while (there is more information)
- read(write) next data from(to) the stream
- close the stream
3. Buffered Streams
The examples shown so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer. Similarly, buffered output streams write data to a buffer. A program can convert an unbuffered stream into a buffered stream using the wrapping.
Example
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
There are four buffered stream classes used to wrap unbuffered streams:
- BufferedInputStream
- BufferedOutputStream (create buffered byte streams )
- BufferedReader
- BufferedWriter (create buffered character streams )
Flushing Buffered Streams
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer. To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered. Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format
CopyLine Example
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class CopyLines { public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l); }
} finally { if (inputStream != null)
{ inputStream.close(); } if (outputStream != null)
{ outputStream.close(); } } } }
I/O from the Command Line
The Java platform supports three Standard Streams:
- Standard Input, accessed through System.in;
- Standard Output, accessed through System.out; and
- Standard Error, accessed through System.err
These standard streams are byte streams. To use Standard Input as a character stream, wrap System.in in InputStreamReader.
InputStreamReader cin = new InputStreamReader(System.in);
ReadingLine Example
import java.io.*;
public class ReadString {
public static void main (String[] args) {
System.out.print("Enter your name: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
// read the username from the command-line;
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadString class
Scanning and Formatting
Programming I/O often involves translating to and from the neatly formatted data humans like to work with. To assist you with these chores, the Java platform provides two APIs. The scanner API breaks input into individual tokens associated with bits of data. The formatting API assembles data into nicely formatted, human-readable form.
Related Posts
5 Responses to File Handling using Input-Output Streams in Java
Leave a Reply Cancel reply
Popular Posts (last 30 days)
- Attendance Management System 1430 view(s)
- Advanced Java Tutorial (For Intermediate) 691 view(s)
- JAVA Graphical User Interface (GUI) 605 view(s)
- Graph Implementation in C++ 474 view(s)
- File Handling using Input-Output Streams in Java 359 view(s)
- Linked lists in C++ 357 view(s)
- UDP Datagram Sockets in Java 317 view(s)
- Sockets and Network Programming in Java 302 view(s)
- Applications of Stack in data structures 293 view(s)
- Circular Linked Lists 281 view(s)








This is really a superb one. My doubts are cleared by seeing this. thanks.
Hi,
So can we not input an ASN.1 file considering its neither text nor binary. If I have to input an ASN.1 file to convert it in to a text file for better readability. What shall I do and what approach shall I take?
Your comments are highly appreciated and awaited
Best Regards
Parsing ASN.1 using Standard Input-output stream might not be a good idea. You can use some parser that specifically deal ASN.1. Following post might be helpful for you.
http://stackoverflow.com/questions/10190795/parsing-asn-1-binary-data-with-java
hi
Very good blog! Do you have any tips and hints for aspiring
writers? I’m hoping to start my own site soon but I’m a little lost on everything.
Would you suggest starting with a free platform like WordPress
or go for a paid option? There are so many options out there that I’m totally confused .. Any recommendations? Cheers!