Java.io Packages Tutorial

Java.io package Tutorial

Java - java.io Package

The java.io package is a standard package of Java SDK. It contains classes for system input and output through data streams, serialization and the file system. This package is very useful as it provides streams to handle input from various sources like keyboard, file system, network etc. On similar patterns, this package has stream classes to write to various kind of sources. This reference will take you through simple and practical methods available in java.io package.

Importing java.io Package

Being an inbuilt package of Java, we're not required to download any external library for java.io package and its all classes can be imported using following syntax:

import java.io.*;

Here we've used * operator to import all classes from java.io package and now any class can be used in the program. In case of specific class, for example InputStream, we can import a class using following syntax:

import java.io.InputStream;

Why java.io Package is used in Java Programs

Java.io package classes contains stream/reader/writer classes to read and write to varied source using a uniform pattern. Following list shows some of the categories of classes of java.io package.

  • Input Streams − Input Streams classes like ByteArrayInputStream, FileInputStream etc. helps to read data from sources like byte array, files as a stream of data and we can read the complete content using buffering as well.

  • Output Streams − On similar pattern, we've OutputStream classes likewise ByteArrayOutputStream, FileOutputStream etc which can be used to write to almost any kind of destination.

  • Error Streams − Error Streams are similar to OutputStreams and are used to write the error to the source.

  • Reader −Reader classes are char oriented and are specialized to read text based content.

  • Writer − Similarly Writer classes are specialized to write text based content to any destination.

Important classes in java.io Package

Following is the list of important classes in java.io.package:

  • BufferedInputStream −The BufferedInputStream class adds functionality to another input stream, the ability to buffer the input and to support the mark and reset methods.

  • BufferedOutputStream −The BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

  • BufferedReader −The BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

  • BufferedWriter −The BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

  • ByteArrayInputStream −The ByteArrayInputStream class contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.

  • ByteArrayOutputStream −The ByteArrayOutputStream class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.

  • CharArrayReader −The CharArrayReader class implements a character buffer that can be used as a character-input stream.

  • CharArrayWriter −The CharArrayWriter class implements a character buffer that can be used as an Writer. The buffer automatically grows when data is written to the stream.

  • Console −The Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine.

  • DataInputStream −The DataInputStream class lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

  • DataOutputStream −The DataOutputStream class lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

  • File −Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion, etc. The File object represents the actual file/directory on the disk.

  • FileDescriptor −The FileDescriptor class instances serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes

  • FileInputStream −The FileInputStream class obtains input bytes from a file in a file system. What files are available depends on the host environment.

  • FileOutputStream −The FileOutputStream class is an output stream for writing data to a File or to a FileDescriptor.

  • FilePermission −The FilePermission class represents access to a file or directory.It consists of a pathname and a set of actions valid for that pathname.

  • FileReader −The FileReader class is a convenience class for reading character files.

  • FileWriter −The FileWriter class is a convenience class for writing character files.

  • FilterInputStream −The FilterInputStream class contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.

  • FilterOutputStream −The FilterOutputStream class is the superclass of all classes that filter output streams.

  • FilterReader −The FilterReader class is for reading filtered character streams.

  • FilterWriter −The FilterWriter class is for writing filtered character streams.

  • InputStream −The InputStream class is the superclass of all classes representing an input stream of bytes. Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.

  • InputStreamReader −The InputStreamReader class is a bridge from byte streams to character streams.It reads bytes and decodes them into characters using a specified charset.

  • LineNumberInputStream −The LineNumberInputStream class is an input stream filter that provides the added functionality of keeping track of the current line number. A line is a sequence of bytes ending with a carriage return character ('\r'), a newline character ('\n'), or a carriage return character followed immediately by a linefeed character.

  • LineNumberReader −The LineNumberReader class is a buffered character-input stream that keeps track of line numbers.A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

  • ObjectInputStream −The ObjectInputStream class deserializes primitive data and objects previously written using an ObjectOutputStream.

  • ObjectInputStream.GetField −The ObjectInputStream.GetField class provide access to the persistent fields read from the input stream.

  • ObjectOutputStream −The ObjectOutputStream class writes primitive data types and graphs of Java objects to an OutputStream.The objects can be read (reconstituted) using an ObjectInputStream.

  • io - ObjectOutputStream.PutField −The ObjectOutputStream.PutField class provide programmatic access to the persistent fields to be written to ObjectOutput.

  • ObjectStreamClass −The ObjectStreamClass class is Serialization's descriptor for classes. It contains the name and serialVersionUID of the class. The ObjectStreamClass for a specific class loaded in this Java VM can be found/created using the lookup method.

  • ObjectStreamField −The ObjectStreamField class is a description of a Serializable field from a Serializable class. An array of ObjectStreamFields is used to declare the Serializable fields of a class.

  • OutputStream −The OutputStream class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.

  • OutputStreamWriter −The OutputStreamWriter class is a bridge from character streams to byte streams. Characters written to it are encoded into bytes using a specified charset.

  • PipedInputStream −The PipedInputStream class is a piped input stream that can be connected to a piped output stream, the piped input stream then provides whatever data bytes are written to the piped output stream.

  • PipedOutputStream −The PipedOutputStream class is a piped output stream that can be connected to a piped input stream to create a communications pipe.

  • PipedReader −The PipedReader class is piped character-input streams.

  • PipedWriter −The PipedWriter class is piped character-output streams.

  • PrintStream −The PrintStream class adds functionality to another output stream, the ability to print representations of various data values conveniently.

  • PrintWriter −The PrintWriter class prints formatted representations of objects to a text-output stream.

  • PushbackInputStream −The PushbackInputStream class adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.

  • PushbackReader −The PushbackReader class is a character-stream reader that allows characters to be pushed back into the stream.

  • RandomAccessFile −The RandomAccessFile class file behaves like a large array of bytes stored in the file system.Instances of this class support both reading and writing to a random access file.

  • Reader −The Reader class is a abstract class for reading character streams.

  • SequenceInputStream −The SequenceInputStream class represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.

  • SerializablePermission −The SerializablePermission class is for Serializable permissions. A SerializablePermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.The target name is the name of the Serializable permission.

  • StreamTokenizer −The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

  • StringBufferInputStream −The StringBufferInputStream class allows an application to create an input stream in which the bytes read are supplied by the contents of a string. Applications can also read bytes from a byte array by using a ByteArrayInputStream.Only the low eight bits of each character in the string are used by this class. This class has been deprecated by Oracle and should not be used any more.

  • StringReader −The StringReader class is a character stream whose source is a string.

  • StringWriter −The StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string.Closing a StringWriter has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

  • Writer −The Writer class is a abstract class for writing to character streams.

Examples of java.io Package

Practice the following examples to learn the concept and usage of java.io package clasess.

Example of java.io.ByteArrayInputStream

The following program illustrates several of the methods supported by ByteArrayInputStream −

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteStreamTest {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
         
         int b =0;
         
         // read till the end of the stream
         while((b = bais.read())!=-1) {
            
            // convert byte to character
            char c = (char)b;
            
            // print
            System.out.println("byte :"+b+"; char : "+ c);
            
         }
         System.out.print(bais.read()+" Reached the end");
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

byte :65; char : A
byte :66; char : B
byte :67; char : C
byte :68; char : D
byte :69; char : E
-1 Reached the end

Example of java.io.ByteArrayOutputStream

The following program illustrates several of the methods supported by ByteArrayOutputStream −

package com.tutorialspoint;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
   public static void main(String[] args) throws Exception {
      ByteArrayOutputStream baos = null;
      BufferedOutputStream bos = null;
		
      try {
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();

         // create new BufferedOutputStream with baos
         bos = new BufferedOutputStream(baos);
			
         // assign integer
         int b = 87;

         // write to stream
         bos.write(b);

         // force the byte to be written to baos
         bos.flush();
			
         // convert ByteArrayOutputStream to bytes
         byte[] bytes = baos.toByteArray();	

         // prints the byte
         System.out.println(bytes[0]);
         
      } catch(IOException e) {
         // if I/O error occurs.
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(baos!=null)
            baos.close();
         if(bos!=null)
            bos.close();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

87

Example of java.io.PrintWriter

The following program illustrates several of the methods supported by PrintWriter −

package com.tutorialspoint;

import java.io.*;

public class PrintWriterDemo {
   public static void main(String[] args) {
      String s = "Hello world.";
      
      try {
         // create a new writer
         PrintWriter pw = new PrintWriter(System.out);

         // print string
         pw.print(s);

         // change the line
         pw.println();

         // print another string
         pw.print("This is an example.");

         // flush the writer
         pw.flush();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Hello world.
This is an example.

When java.io Package is Used?

Whenever we need to perform i/o operations, we can rely on i/o classes present in java.io package. This reference has been prepared for the beginners to help them understand the basic functionality related to all the methods available in Java.io package.

Prerequisites

Before you start doing practice with various types of examples given in this reference, I'm making an assumption that you are already aware of basic Java Programming.

Advertisements