Java File I/O: A Concise Tutorial Just An Hour | ACTE
Java File I-O Tutorial

Java File I/O: A Concise Tutorial Just An Hour – FREE

Last updated on 08th Jul 2020, Blog, Tutorials

About author

Divan Singh (Java Developer )

Divan Singh is a Java Developer and contributes in-depth articles on various Big Data Technologies. He also has experience with Hadoop, Microservices, Commvault, and a few BI tools. And he has expertise in Python, R, Java, Ruby, Pig, SQL, Hadoop, HDFS, Yarn, Mahout, Pig, Hive, Spark, Power BI, SSRS, Tableau, BOBJ, and Cognos.

(5.0) | 18974 Ratings 870

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.

We can perform file handling in Java by Java I/O API.

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.

  • System.out: standard output stream
  • System.in: standard input stream
  • System.err: standard error stream

Let’s see the code to print output and an error message to the console.

  • System.out.println(“simple message”);  
  • System.err.println(“error message”);  

Let’s see the code to get input from console.

  • int i=System.in.read();//returns ASCII code of 1st character  
  • System.out.println((char)i);//will print the character  

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.

    Subscribe For Free Demo

    [custom_views_post_title]

    InputStream

    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

    MethodsDescription
    1) public void write(int)throws IOExceptionis used to write a byte to the current output stream.
    2) public void write(byte[])throws IOExceptionis used to write an array of byte to the current output stream.
    3) public void flush()throws IOExceptionflushes the current output stream.
    4) public void close()throws IOExceptionis used to close the current output stream.

    OutputStream Hierarchy

    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

    MethodsDescription
    1) public abstract int read()throws IOExceptionreads the next byte of data from the input stream. It returns -1 at the end of the file.
    2) public int available()throws IOExceptionreturns an estimate of the number of bytes that can be read from the current input stream.
    3) public void close()throws IOExceptionis used to close the current input stream.

    InputStream Hierarchy

    InputStream-Hierarchy

    Java FileOutputStream Class

    Java FileOutputStream is an output stream used for writing data to a file.

    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.

    FileOutputStream class methods

    MethodDescription
    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 file output stream.
    void write(byte[] ary, int off, int len)It is used to write len bytes from the byte array starting at offset off to 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 file output stream.
    FileDescriptor getFD()It is used to return the file descriptor associated with the stream.
    void close()It is used to closes the file output stream.

    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. 

    Course Curriculum

    Get On-Demand Java Certification Course to Enhance Your Career

    Weekday / Weekend BatchesSee Batch Details
    MethodDescription
    int available()It is used to return the estimated number of bytes that can be read from the input 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, int len)It is used to read up to len bytes of data from the input stream.
    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 input stream.
    FileDescriptor getFD()It is used to return the FileDescriptor object.
    protected void finalize()It is used to ensure that the close method is call when there is no more reference to the file input stream.
    void close()It is used to closes the stream.

    Java BufferedOutputStream Class

    Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

    For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let’s see the syntax for adding the buffer in an OutputStream:

    Java BufferedOutputStream class constructors

    Constructor Description
    BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.
    BufferedInputStream(InputStream IS, int size) It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

    Java BufferedOutputStream class methods

    MethodDescription
    void write(int b)It writes the specified byte to the buffered output stream.
    void write(byte[] b, int off, int len)It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset
    void flush()It flushes the buffered output stream.

    Java BufferedInputStream Class

    Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.

    The important points about BufferedInputStream are:

    • 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.
    • When a BufferedInputStream is created, an internal buffer array is created.

    Java BufferedInputStream class constructors

    ConstructorDescription
    BufferedInputStream(InputStream IS)It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.
    BufferedInputStream(InputStream IS, int size)It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

    Java BufferedInputStream class methods

    MethodDescription
    int available()It returns an estimate number of bytes that can be read from the input stream 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, int ln)It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.
    void close()It closes the input stream and releases any of the system resources associated with the stream.
    void reset()It repositions the stream at a position the mark method was last called on this input 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 markSupported()It tests for the input stream to support the mark and reset methods.

    Java SequenceInputStream Class

    Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by one).

    Constructors of SequenceInputStream class

    MethodDescription
    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.

    Methods of SequenceInputStream class

    MethodDescription
    int read()It is used to read the next byte of data from the input stream.
    int read(byte[] ary, int off, int len)It is used to read len bytes of data from the input stream into the array of bytes.
    int available()It is used to return the maximum number of byte that can be read from an input stream.
    void close()It is used to close the input stream.

    Java ByteArrayOutputStream Class

    Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.

    The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

    The buffer of ByteArrayOutputStream automatically grows according to data.

    Java ByteArrayOutputStream class constructors

    ConstructorDescription
    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.

    Java ByteArrayOutputStream class methods

    MethodDescription
    int size()It is used to returns the current size of a buffer.
    byte[] toByteArray()It is used to create a newly allocated byte array.
    String toString()It is used for converting the content into a string decoding bytes using a platform default character set.
    String toString(String charsetName)It is used for converting the content into a string decoding bytes using a specified charsetName.
    void write(int b)It is used for writing the byte specified to the byte array output stream.
    void write(byte[] b, int off, int lenIt is used for writing len bytes from specified byte array starting from the offset off to the byte array output stream.
    void writeTo(OutputStream out)It is used for writing the complete content of a byte array output stream to the specified output stream.
    void reset()It is used to reset the count field of a byte array output stream to zero value.
    void close()It is used to close the ByteArrayOutputStream.

    Java ByteArrayInputStream Class

    The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the name suggests, it can be used to read byte array as input stream.

    Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array.

    The buffer of ByteArrayInputStream automatically grows according to data.

    Java ByteArrayInputStream class constructors

    ConstructorDescription
    ByteArrayInputStream(byte[] ary)Creates a new byte array input stream which uses ary as its buffer array.
    ByteArrayInputStream(byte[] ary, int offset, int len)Creates a new byte array input stream which uses ary as its buffer array that can read up to specified len bytes of data from an array.

    Java ByteArrayInputStream class methods

    MethodDescription
    int available()It is used to return the number of remaining bytes that can be read from the input stream.
    int read()It is used to read the next byte of data from the input stream.
    int read(byte[] ary, int off, int len)It is used to read up to len bytes of data from an array of bytes in the input stream.
    boolean markSupported()It is used to test the input stream for mark and reset method.
    long skip(long x)It is used to skip the x bytes of input from the input stream.
    void mark(int readAheadLimit)It is used to set the current marked position in the stream.
    void reset()It is used to reset the buffer of a byte array.
    void close()It is used for closing a ByteArrayInputStream.

    Java DataOutputStream Class

    Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

    Java application generally uses the data output stream to write data that can later be read by a data input stream.

    Java DataOutputStream class methods

    Course Curriculum

    Get In-Depth Knowledge on Java Training from Industry Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    MethodDescription
    int size()It is used to return the number of bytes written to the data output stream.
    void write(int b)It is used to write the specified byte to the underlying output stream.
    void write(byte[] b, int off, int len)It is used to write len bytes of data to the output stream.
    void writeBoolean(boolean v)It is used to write Boolean to the output stream as a 1-byte value.
    void writeChar(int v)It is used to write char to the output stream as a 2-byte value.
    void writeChars(String s)It is used to write string to the output stream as a sequence of characters.
    void writeByte(int v)It is used to write a byte to the output stream as a 1-byte value.
    void writeBytes(String s)It is used to write string to the output stream as a sequence of bytes.
    void writeInt(int v)It is used to write an int to the output stream
    void writeShort(int v)It is used to write a short to the output stream.
    void writeShort(int v)It is used to write a short to the output stream.
    void writeLong(long v)It is used to write a long to the output stream.
    void writeUTF(String str)It is used to write a string to the output stream using UTF-8 encoding in portable manner.
    void flush()It is used to flushes the data output stream.

    Java DataInputStream Class

    Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way.

    Java application generally uses the data output stream to write data that can later be read by a data input stream.

    Java DataInputStream class Methods

    MethodDescription
    int read(byte[] b)It is used to read the number of bytes from the input stream.
    int read(byte[] b, int off, int len)It is used to read len bytes of data from the input stream.
    int readInt()It is used to read input bytes and return an int value.
    byte readByte()It is used to read and return the one input byte.
    char readChar()It is used to read two input bytes and returns a char value.
    double readDouble()It is used to read eight input bytes and returns a double value.
    boolean readBoolean()It is used to read one input byte and return true if byte is non zero, false if byte is zero.
    int skipBytes(int x)It is used to skip over x bytes of data from the input stream.
    String readUTF()It is used to read a string that has been encoded using the UTF-8 format.
    void readFully(byte[] b)It is used to read bytes from the input stream and store them into the buffer array.
    void readFully(byte[] b, int off, int len)It is used to read len bytes from the input stream.

    Java FilterOutputStream Class

    Java FilterOutputStream class implements the OutputStream class. It provides different sub classes such as BufferedOutputStream and DataOutputStream to provide additional functionality. So it is less used individually.

    Java FilterOutputStream class Methods

    MethodDescription
    void write(int b)It is used to write the specified byte to the output stream.
    void write(byte[] ary)It is used to write ary.length byte to the output stream.
    void write(byte[] b, int off, int len)It is used to write len bytes from the offset off to the output stream.
    void flush()It is used to flushes the output stream.
    void close()It is used to close the output stream.

    Java FilterInputStream Class

    Java FilterInputStream class implements the InputStream. It contains different sub classes as BufferedInputStream, DataInputStream for providing additional functionality. So it is less used individually.

    Java FilterInputStream class Methods

    Java Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    MethodDescription
    int available()It is used to return an estimate number of bytes that can be read from the input stream.
    int read()It is used to read the next byte of data from the input stream.
    int read(byte[] b)It is used to read up to byte.length bytes of data from the input stream.
    long skip(long n)It is used to skip over and discards n bytes of data from the input stream.
    boolean markSupported()It is used to test if the input stream support mark and reset method.
    void mark(int readlimit)It is used to mark the current position in the input stream.
    void reset()It is used to reset the input stream.
    void close()It is used to close the input stream.

    Conclusion

    This module introduced you to streams which are the foundation of input and output in Java. In this module, you learned what streams are, where streams come from, and when you should use streams.

    A Java program can read from multiple data sources and destinations, like a file on your storage device, another application, an array in memory, a network connection, and others. Shows different I/O streams, input streams and output streams and how they are connected to data sources and destinations.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free