File Handling
File Handling
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
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 the 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.
Useful methods of OutputStream
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
Useful methods of InputStream
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It return
IOException at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException from the current input stream.
InputStream Hierarchy
If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream
class. But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the
output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset o
int len) the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
Output:
Success...
testout.txt
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.
Java FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can
also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
int available() It is used to return the estimated number of bytes that can be read from the i
stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, It is used to read up to len bytes of data from the input stream.
int len)
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file
stream.
protected void finalize() It is used to ensure that the close method is call when there is no more refer
to the file input stream.
Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which
is 87 (in byte form). To see the text, you need to convert it into character.
Output:
W
Java FileInputStream example 2: read all
characters
1. package com.javatpoint;
2.
3. import java.io.FileInputStream;
4. public class DataStreamExample {
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("D:\\testout.txt");
8. int i=0;
9. while((i=fin.read())!=-1){
10. System.out.print((char)i);
11. }
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
Output:
Welcome to javaTpoint
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's
see the syntax for adding the buffer in an OutputStream:
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for wr
the data to the specified output stream.
BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is used for wr
int size) the data to the specified output stream with a specified buffer
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, It write the bytes from the specified byte-input stream into a specified byte a
int len) starting with the given offset
Output:
Success
testout.txt
Welcome to javaTpoint.
o When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.
int available() It returns an estimate number of bytes that can be read from the input st
without blocking by the next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, It read the bytes from the specified byte-input stream into a specified byte a
int ln) starting with the given offset.
void close() It closes the input stream and releases any of the system resources associated
the stream.
void reset() It repositions the stream at a position the mark method was last called on this
stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean It tests for the input stream to support the mark and reset methods.
markSupported()
1. package com.javatpoint;
2.
3. import java.io.*;
4. public class BufferedInputStreamExample{
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("D:\\testout.txt");
8. BufferedInputStream bin=new BufferedInputStream(fin);
9. int i;
10. while((i=bin.read())!=-1){
11. System.out.print((char)i);
12. }
13. bin.close();
14. fin.close();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Output:
javaTpoint