Java IO Tutorial

19 Feb, 2022
Java programming language comes with a variety of APIs that helps the developers to code more efficiently. One of those APIs is Java IO API. Java IO API helps the users to read and write data. In simple words, we can say that the Java IO helps the users to take the input and produce output based on that input. Almost every application or code requires some input and output produced based on that input. So let’s start with Java IO Tutorial.
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 operations 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.
The Java IO API is placed in the java.io package. This package comprises almost all classes that a user requires to perform input and output (I/O) in Java. The Java IO package focuses on input and output to files, network streams, etc. However, the Java IO package does not include classes to open network sockets which are essential for network communication. 
The java.io package generally involves reading basic information from a source and writing it to a destination. The below figure perfectly demonstrates the principle of a program taking input data from a source and producing output based on it to some destination. 
In the programming world, a stream can be described as a series of data. It is known as a stream because it is similar to a stream of water that continues to flow. Java IO streams are flows of data that a user can either read from or write to. Like an array, a stream has no concept of indexing the read or write data. A stream is attached to a data origin or a data target.
Java Streams uses two primary streams to read and write the data. These are:
1. InputStream – An input stream is used to read the data from a source in a Java application. Data can be anything, a file, an array, a peripheral device, or a socket. In Java, the class java.io.InputStream is the base class for all Java IO input streams.
Methods of Java IO InputStreams
read() – The read() method is used to read the next byte of data from the Input Stream. The value byte is passed on a scale of 0 to 255. If no byte is free because the end of the stream has arrived, the value -1 is passed. mark(int arg) – The mark(int arg) method is used to mark the current position of the input stream. It sets read to limit, i.e., the maximum number of bytes that can be read before the mark position becomes invalid. reset() – The reset() method  is invoked by mark() method. It changes the position of the input stream back to the marked position. close() – The close() method is used to close the input stream and releases system resources associated with this stream to Garbage Collector. read(byte [] arg) – The read(byte [] arg) method is used to read the number of bytes of arg.length from the input stream to the buffer array arg. The bytes read by read() method are returned as an int. If the length is zero, then no bytes are read, and 0 is returned unless there is an effort to read at least one byte. skip(long arg) – The skip(long arg) method is used to skip and discard arg bytes in the input stream. markSupported() – The markSupported() method tests if the inputStream supports the mark and reset methods. The markSupported method of Java IO InputStream yields false by default.
read() – The read() method is used to read the next byte of data from the Input Stream. The value byte is passed on a scale of 0 to 255. If no byte is free because the end of the stream has arrived, the value -1 is passed. 
mark(int arg) – The mark(int arg) method is used to mark the current position of the input stream. It sets read to limit, i.e., the maximum number of bytes that can be read before the mark position becomes invalid. 
reset() – The reset() method  is invoked by mark() method. It changes the position of the input stream back to the marked position. 
close() – The close() method is used to close the input stream and releases system resources associated with this stream to Garbage Collector. 
read(byte [] arg) – The read(byte [] arg) method is used to read the number of bytes of arg.length from the input stream to the buffer array arg. The bytes read by read() method are returned as an int. If the length is zero, then no bytes are read, and 0 is returned unless there is an effort to read at least one byte. 
skip(long arg) – The skip(long arg) method is used to skip and discard arg bytes in the input stream. 
markSupported() – The markSupported() method tests if the inputStream supports the mark and reset methods. The markSupported method of Java IO InputStream yields false by default.
Example of Java IO InputStream:
Java
// Java program illustrates the use of// the Java IO InputStream methods import java.io.*;   public class InputStreamExample{    public static void main(String[] args) throws Exception    {        InputStream input = null;        try {               input = new FileInputStream("Text.txt");               // read() method - reading and printing Characters            // one by one            System.out.println("Char - "+(char)input.read());            System.out.println("Char - "+(char)input.read());               // mark() - read limiting the 'input' input stream            input.mark(0);               // skip() - it results in skipping of 'e' in Ge'e'ksforGeeks            input.skip(1);            System.out.println("skip() method comes to play");            System.out.println("mark() method comes to play");            System.out.println("Char - "+(char)input.read());            System.out.println("Char - "+(char)input.read());               boolean check = input.markSupported();            if (input.markSupported())            {                // reset() method - repositioning the stream to                // marked positions.                input.reset();                System.out.println("reset() invoked");                System.out.println("Char - "+(char)input.read());                System.out.println("Char - "+(char)input.read());            }            else                System.out.println("reset() method not supported.");                  System.out.println("input.markSupported() supported"+                              " reset() - "+check);           }        catch(Exception e)        {            // in case of I/O error            e.printStackTrace();        }        finally        {            if (input!=null)            {                // Use of close() - closing the file                // and releasing resources                input.close();            }        }    }}
Text.txt file used in the above code has the following content in it: 
GeeksforGeeks
Output:
Note – This code won’t run on an online IDE as no such file is present there. You can run this code on your System to check it’s working.
2. OutputStream – An output stream is used to write data (a file, an array, a peripheral device, or a socket) to a destination. In Java, the class java.io.OutputStream is the base class for all Java IO output streams.
Methods of Java IO OutputStreams
flush() – The flush() method is used for flushing the outputStream This method forces the buffered output bytes to be written out. close() – The close() method is used to close the outputStream and to release the system resources affiliated with the stream. write(int b) – The write(int b) method is used to write the specified byte to the outputStream. write(byte [] b) – The write(byte [] b) method is used to write bytes of length b.length from the specified byte array to the outputStream. 
flush() – The flush() method is used for flushing the outputStream This method forces the buffered output bytes to be written out. 
close() – The close() method is used to close the outputStream and to release the system resources affiliated with the stream. 
write(int b) – The write(int b) method is used to write the specified byte to the outputStream. 
write(byte [] b) – The write(byte [] b) method is used to write bytes of length b.length from the specified byte array to the outputStream. 
Java
// Java program to demonstrate OutputStreamimport java.io.*; public class OutputStreamExample {    public static void main(String args[]) throws Exception    {        OutputStream output            = new FileOutputStream("file.txt");        byte b[] = { 65, 66, 67, 68, 69, 70 };         // illustrating write(byte[] b) method        output.write(b);         // illustrating flush() method        output.flush();         // illustrating write(int b) method        for (int i = 71; i < 75; i++) {            output.write(i);        }         output.flush();         // close the stream        output.close();    }}
Output: When we run the program, the file.txt file is filled with the following content.
ABCDEFGHIJ
Note – This code won’t run on an online IDE as no such file is present there. You can run this code on your System to check it’s working.
The Streams in Java IO are of the following types:
1. Byte Streams – Java byte streams are the ones that are used to implement the input and output of 8-bit bytes. Several classes are affiliated with byte streams in Java. However, the most generally practiced classes are FileInputStream and FileOutputStream.
Different classes of Byte Streams
2. Character Streams – Java Character streams are the ones that are used to implement the input and output for 16-bit Unicode. Several classes are associated with character streams in Java, but the most commonly used classes are FileReader and FileWriter. Internally, the FileReader class uses FileInputStream and the FileWriter class uses FileOutputStream. Nevertheless, the significant contrast is that FileReader and FileWriter read and write two bytes, respectively.
Different classes of Character Streams:
3. Standard Streams – All the programming languages assist standard I/O, where the user’s program can take input from a keyboard and then produce an output on the computer screen. Just like C and C++ have three standard streams, STDIN, STDOUT, and STDERR, Java also provides the following three standard streams: 
Standard Input – The Standard Input class is used to accept input data to the user’s program. Usually, a keyboard is utilized as a standard input stream and described as System.in. 
Standard Output – This class is used to output the data generated by the user’s program, and usually, a computer screen is used for standard output stream and described as System.out. 
Standard Error – The Standard error class is used to output the data having an error that is generated by the user’s program. Normally, a computer screen is utilized for standard error stream and described as System.err. 
Example of Standard Streams in Java IO
Java
// Java program to illustrate// the Standard Java IO Streams import java.io.*;import java.util.*; public class StandardStreamsExample {    public static void main(String[] args)    {        try {             // using System.in class to import the Scanner            // that helps in taking input from the user            Scanner s = new Scanner(System.in);             // using System.out class print the output on            // the screen using .print() ans .println()            // methods            System.out.print("Enter the value of A : ");            int a = s.nextInt();            System.out.println("Value of A is : " + a);             System.out.print("Enter the value of B : ");            int b = s.nextInt();            System.out.println("Value of B is : " + b);             System.out.println(                "Result of division A/B is : " + (a / b));        }        catch (Exception ex) {             // using System.err class to print the error            // message            System.err.print("Exception message : "                             + ex.getMessage());        }    }}
Output
The Java.io.Console class implements programs to receive the character-based console device, if any, affiliated with the prevailing Java virtual machine. The Console class was added to the package java.io in Java Development Kit 6 (JDK 6).
The Java Console class is be used to take input from the console. It presents methods to read texts and passwords. If a user reads the password using the Console class, it will not be disclosed to the user. The java.io.Console class is connected to the system console internally. 
Characteristics of Java IO Console
Java IO Console is used to read from and write to the console if one exists.
The console is fundamentally a support class because most of its functionality is achievable through System.in and System.out. However, its effectiveness can clarify some console interactions, particularly when reading strings from the console.
The console has no constructors. Instead, if a user wants to obtain a Console object, then it can be done by calling System.console( ).
If a console is available, then a reference of that console is returned. Otherwise, null is returned. A console class is not feasible in all cases. Thus, in case of no console, null is returned.
Methods of Java IO Console
Input and output streams are fundamentally byte-based. Java IO Reader and writer depends on the characters, which can have varying amplitudes depending on the character set. For instance, ASCII and ISO Latin-1 handle one-byte characters. Unicode uses two-byte characters. UTF-8 handles characters of different amplitudes (among one and three bytes). As characters are eventually comprised of bytes, readers practice their input from streams. However, they transform those bytes into characters according to a particularized encoding setup before catching them along. Furthermore, writers transform characters to bytes according to a particularized encoding before writing them onto any underlying stream.
The java.io.Reader and java.io.Writer classes are abstract superclasses. These superclasses help in reading and writing character-based data. These subclasses are important for managing the transformation among various character sets. In Java IO API, there are nine reader and eight writer classes, all in the java.io package.
A reader is used when a user wants to read character-based data from a source of the data. The Java IO Reader class is an abstract class that is used for expressing character streams. The only programs that a subclass needs to implement are read(char[], int, int) and close() methods. Many subclasses of the Reader class will override some of the methods shown below. However, most subclasses produce tremendous efficiency, additional functionality, or both.
Methods of Java IO Reader
close() – This method is used to close the stream and release any associated system resources. Once the stream has been closed, further methods invocations like read(), mark(), or skip() will throw an IOException. In Java IO, closing an earlier-ended stream has no effect. mark(int readAheadLimit) – This method is utilized to check the ongoing place in the stream. The following calls to reset() method will try to change the position of the stream to this point. In Java IO Reader, all the character-input streams do not support the mark() operation. markSupported() – This process determines whether this stream sustains the mark() operation or not. The default implementation always returns false. All the subclasses of the Java IO Reader should call this method. read() – This method is used to read a single character. The read() method is obstructed till a character is feasible, an I/O error happens, or the stream is ended.  All the subclasses of the Java IO Reader class that intend to sustain adequate single-character input should override this method. read(char[] cbuf) – This method is used to read characters into an array. This method is obstructed till some information is possible, an I/O error occurs, or the end of the stream is reached. read(char[] cbuf, int off, int len) – This method is used to read the characters in a part of an array. This method is obstructed till a character is feasible, an I/O error happens, or the stream is ended.  read(CharBuffer target) – This method strives to read characters within the particularized character buffer. The buffer target is utilized like a container of characters.  ready() – This method is used to tell whether this stream is ready to be read. reset() – This method is used to reset the stream. If the stream has been marked, then this method tries to reposition the stream at the mark. If the stream has not been checked, then strive to reset it in some way relevant to the appropriate stream, for example, generally used by repositioning it to its starting point. Not all character-input streams sustain the reset() process, and some help the reset() without sustaining mark(). skip(long n) – This method is used to skip characters. This method is blocked till some information is available, an I/O error occurs, or the end of the stream is reached.
close() – This method is used to close the stream and release any associated system resources. Once the stream has been closed, further methods invocations like read(), mark(), or skip() will throw an IOException. In Java IO, closing an earlier-ended stream has no effect. 
mark(int readAheadLimit) – This method is utilized to check the ongoing place in the stream. The following calls to reset() method will try to change the position of the stream to this point. In Java IO Reader, all the character-input streams do not support the mark() operation. 
markSupported() – This process determines whether this stream sustains the mark() operation or not. The default implementation always returns false. All the subclasses of the Java IO Reader should call this method. 
read() – This method is used to read a single character. The read() method is obstructed till a character is feasible, an I/O error happens, or the stream is ended.  All the subclasses of the Java IO Reader class that intend to sustain adequate single-character input should override this method. 
read(char[] cbuf) – This method is used to read characters into an array. This method is obstructed till some information is possible, an I/O error occurs, or the end of the stream is reached. 
read(char[] cbuf, int off, int len) – This method is used to read the characters in a part of an array. This method is obstructed till a character is feasible, an I/O error happens, or the stream is ended.  
read(CharBuffer target) – This method strives to read characters within the particularized character buffer. The buffer target is utilized like a container of characters. 
 ready() – This method is used to tell whether this stream is ready to be read. 
reset() – This method is used to reset the stream. If the stream has been marked, then this method tries to reposition the stream at the mark. If the stream has not been checked, then strive to reset it in some way relevant to the appropriate stream, for example, generally used by repositioning it to its starting point. Not all character-input streams sustain the reset() process, and some help the reset() without sustaining mark(). 
skip(long n) – This method is used to skip characters. This method is blocked till some information is available, an I/O error occurs, or the end of the stream is reached.
Different classes of Java IO Reader
Example of Java IO Reader
Java
// Java Program to illustrate the// use of Java IO Reader methodsimport java.io.*; public class ReaderExample {    public static void main(String[] args) {         // Creates a character array of size 100.        char[] array = new char[100];         try {            // Creating a reader object using the class FileReader            Reader input = new FileReader("file.txt");             // Checks if reader is ready            System.out.println("Is there data in the stream?  " + input.ready());             // Reads characters            input.read(array);            System.out.println("Data in the stream -");            System.out.println(array);             // Closes the reader            input.close();        }         catch(Exception e) {            e.getStackTrace();        }    }}
file.txt file used in the above code has the following content in it –
Hello Geeks.
Output
Note – This code won’t run on an online IDE as no such file is present there. You can run this code on your System to check it’s working.
Java IO Writer is an abstract class utilized for writing to the character streams. The only methods in Java IO Writer that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override several methods explained here to implement higher efficiency, additional functionality, or both.
Methods of Java IO Writer:
append(char c) – This method is used to add the particularized character to the writer. An invocation of this process of the form out.append(c) performs the same way as the invocation – out.write(c).  append(CharSequence csq) – This method is used to add the designated character sequence to the writer. An invocation of this process of the form out.append(csq) functions in precisely the identical style as the invocation – out.write(csq.toString()). append(CharSequence csq, int start, int end) – This method is used to add a subsequence of the particularized character sequence to the writer. It adds a subsequence of the detailed character sequence to the writer. close() – This method is used to close the stream, flushing it first. Once the stream has been stopped, further write() or flush() methods will provoke an IOException to be thrown. In Java IO Writer, closing an earlier closed stream has no effect. flush() – This method is used for flushing the stream. If the stream has preserved any characters from the multiple write() methods in a buffer, they should be written immediately to their proposed destination. After that, if that destination is a different character or byte stream, it should be flushed. Thus one invocation method flush() will flush all the barriers or buffers in a series of Writers and OutputStreams. write(char[] cbuf) – This method is used to write an array of characters. write(char[] cbuf, int off, int len) – This method is used to write a portion of an array of characters. write(int c) – This method is used to print an individual character. The character to be rewritten is displayed in the 16 low-order bits of the provided integer value. It means that the 16 high-order bits are ignored. Subclasses that intend to support efficient single-character output should override this method. write(String str, int off, int len) – This method is used to write a portion of a string.
append(char c) – This method is used to add the particularized character to the writer. An invocation of this process of the form out.append(c) performs the same way as the invocation – out.write(c).  
append(CharSequence csq) – This method is used to add the designated character sequence to the writer. An invocation of this process of the form out.append(csq) functions in precisely the identical style as the invocation – out.write(csq.toString()). 
append(CharSequence csq, int start, int end) – This method is used to add a subsequence of the particularized character sequence to the writer. It adds a subsequence of the detailed character sequence to the writer. 
close() – This method is used to close the stream, flushing it first. Once the stream has been stopped, further write() or flush() methods will provoke an IOException to be thrown. In Java IO Writer, closing an earlier closed stream has no effect. 
flush() – This method is used for flushing the stream. If the stream has preserved any characters from the multiple write() methods in a buffer, they should be written immediately to their proposed destination. After that, if that destination is a different character or byte stream, it should be flushed. Thus one invocation method flush() will flush all the barriers or buffers in a series of Writers and OutputStreams. 
write(char[] cbuf) – This method is used to write an array of characters. 
write(char[] cbuf, int off, int len) – This method is used to write a portion of an array of characters. 
write(int c) – This method is used to print an individual character. The character to be rewritten is displayed in the 16 low-order bits of the provided integer value. It means that the 16 high-order bits are ignored. Subclasses that intend to support efficient single-character output should override this method. 
write(String str, int off, int len) – This method is used to write a portion of a string.
Different classes of Java IO Writer
The list of different classes of Java IO Writer is given below –
Example  of Java IO Writer
Java
// Java Program to illustrate the// use of Java IO Writer methodsimport java.io.*; public class WriterExample {     public static void main(String args[]) {         String data = "Hello Geeks.";         try {            // Creates a Writer using FileWriter            Writer output = new FileWriter("file.txt");              // Writes string to the file            output.write(data);             // Closes the writer            output.close();        }         catch (Exception e) {            e.getStackTrace();        }    }}
Output
When we run the program, the file.txt file is filled with the following content.
Hello Geeks.
Note – This code won’t run on an online IDE as no such file is present there. You can run this code on your System to check it’s working.
The Java IO File class is Java’s description of a file or pathname of a directory. Since file and directory names have distinctive arrangements on various platforms, a naive string is not sufficient to describe them. The File class comprises various approaches for operating with the pathname, removing and renaming files, generating new directories, arranging the contents of a list, and managing numerous general properties of files and directories.
Java IO File is an ideal illustration of files and pathnames of directories.
A pathname, whether general or in string pattern, can be either fixed or contingent. The origin of an ideal pathname may be accomplished by invoking the getParent() process of the Java IO File class.
First of all, a user should build an object of the File class by giving it the filename or directory name. A file method may execute limitations to specific actions on the real file-system object, such as reading and writing. These constraints are collectively identified as access permissions.
Instances of the File class are immutable. That is, once created, the abstract pathname denoted by a File object will nevermore change.
canExecute() – This method is used to examine whether the application can accomplish the file expressed by the abstract pathname. canWrite() – This method is used to test whether the application can transform the file expressed by the abstract pathname or not. canRead() – This method is used to examine whether the application can read the given file signified by the abstract pathname. getName() – This method is used to return the file or directory name denoted by the abstract pathname. getPath() – This method is used to convert the abstract pathname into a pathname string. getAbsolutePath() – This method is used to return the absolute pathname string of the abstract pathname. getParent() – This method is used to return the pathname string of the abstract pathname’s parent. exists() – This method is used to test whether the file or directory expressed by the abstract pathname exists or not. length() – This method is used to return the length of the file denoted by the abstract pathname. isDirectory() – This method is used to test whether the file denoted by the pathname is a directory.
canExecute() – This method is used to examine whether the application can accomplish the file expressed by the abstract pathname. 
canWrite() – This method is used to test whether the application can transform the file expressed by the abstract pathname or not. 
canRead() – This method is used to examine whether the application can read the given file signified by the abstract pathname. 
getName() – This method is used to return the file or directory name denoted by the abstract pathname. 
getPath() – This method is used to convert the abstract pathname into a pathname string. 
getAbsolutePath() – This method is used to return the absolute pathname string of the abstract pathname. 
getParent() – This method is used to return the pathname string of the abstract pathname’s parent. 
exists() – This method is used to test whether the file or directory expressed by the abstract pathname exists or not. 
length() – This method is used to return the length of the file denoted by the abstract pathname. 
isDirectory() – This method is used to test whether the file denoted by the pathname is a directory.
Example of Java IO File
Java
// Java program to illustrate the use// of Java IO File methods import java.io.File; public class FileExample{    public static void main(String[] args) {         // taking the file or directory as a input        // from the command line argument (args)        String fname =args[0];           // passing the file or directory name to File object        File f = new File(fname);           // applying the methods of the File        // class on the File object        System.out.println("File name - "+f.getName());        System.out.println("Path - "+f.getPath());        System.out.println("Absolute path - " +f.getAbsolutePath());        System.out.println("Parent - "+f.getParent());        System.out.println("Exists - "+f.exists());             if(f.exists())        {            System.out.println("Is writable - "+f.canWrite());            System.out.println("Is readable - "+f.canRead());            System.out.println("Is a directory - "+f.isDirectory());            System.out.println("File Size in bytes "+f.length());        }    }}
Output
Geeks.txt file used in the above code has the following content in it –
Hello Geeks
Note – This code won’t run on an online IDE as no such file is present there. You can run this code on your System to check it’s working.
anikakapoor
abhishek0719kadiyan
simmytarika5
nishkarshgandhi
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.