JAVA I/O and FILE
Java IO API provides classes and methods to handle input and output operations efficiently. It allows
reading data from various sources and writing data to different destinations, essential for almost all Java
applications.
Supports reading from files, user input and other sources.
Enables writing to files, consoles and other output destinations.
Includes byte streams and character streams for flexible I/O [Link] from files,
What is Java IO
Java IO (Input/Output) is used to process input and produce output. Java uses the concept of streams to
make I/O operations efficient.
The [Link] package provides all the classes required for input and output.
It supports operations like file handling, console input/output and working with data streams.
Note: The [Link] package does not handle network sockets (that’s done via [Link]).
Java IO Streams
A stream is a sequence of data that flows from a source to a destination, similar to water flowing in a
pipe.
Input Stream
Output Stream
Unlike arrays, streams don’t support random access (no indexing). Data flows sequentially.
1
InputStream in Java
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 [Link] is the base class for all
Java IO input streams.
Example: Java program illustrates the use of the Java IO InputStream.
import [Link].*;
public class InputStreamExample
{
public static void main(String[] args) throws Exception
{
InputStream input = null;
try {
input = new FileInputStream("[Link]");
// read() method - reading and printing Characters one by one
[Link]("Char - "+(char)[Link]());
[Link]("Char - "+(char)[Link]());
// mark() - read limiting the 'input' input stream
[Link](0);
// skip() - it results in skipping of 'e' in Ge'e'ksforGeeks
[Link](1);
[Link]("skip() method comes to play");
2
[Link]("mark() method comes to play");
[Link]("Char - "+(char)[Link]());
[Link]("Char - "+(char)[Link]());
boolean check = [Link]();
if ([Link]())
{
// reset() method - repositioning the stream to marked positions.
[Link]();
[Link]("reset() invoked");
[Link]("Char - "+(char)[Link]());
[Link]("Char - "+(char)[Link]());
}
else
[Link]("reset() method not supported.");
[Link]("[Link]() supported"+" reset() - "+check);
}
catch(Exception e)
{
// in case of I/O error
[Link]();
}
finally
{
if (input!=null)
{
// Use of close() - closing the file and releasing resources
[Link]();
}
}
}
}
3
OUTPUT:
OutputStream in Java
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 [Link] is the base class for all Java IO output streams.
Example: Java program illustrates the use of the Java IO OutputStream.
import [Link].*;
public class OutputStreamExample {
public static void main(String args[]) throws Exception
{
OutputStream output = new FileOutputStream("[Link]");
byte b[] = { 65, 66, 67, 68, 69, 70 };
// illustrating write(byte[] b) method
[Link](b);
4
// illustrating flush() method
[Link]();
// illustrating write(int b) method
for (int i = 71; i < 75; i++) {
[Link](i);
}
[Link]();
// close the stream
[Link]();
}
}
OUTPUT:
When we run the program, the [Link] 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.
Types of Streams in Java IO
The Streams in Java IO are of the following types:
5
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
InputStream: This is an abstract class that defines stream input.
FileInputStream: This is used to reads from a file.
DataInputStream: It contains a method for reading java standard datatypes.
BufferedInputStream: It is used for Buffered Input Stream.
PrintStream: This class comprises the commonly used print() and println() methods.
OutputStream: This is an abstract class that describes stream output.
FileOutputStream: This class is used to write to a file.
DataOutputStream: This contains a method for writing java standard data types.
BufferedOutputStream : This is used for Buffered Output Stream.
CHARACTER STREAMS
In Java, character streams handle input and output of 16-bit Unicode characters. The most commonly
used classes are FileReader (internally uses FileInputStream) and FileWriter (internally uses
FileOutputStream). Unlike byte streams, they read and write data as characters (two bytes at a time).
Different classes of Character Streams
Reader: This is an abstract class that defines character stream input.
Writer: This is an abstract class that defines character stream output.
FileReader: This is an input stream that reads from the file.
FileWriter: This is used to the output stream that writes to the file.
BufferedReader: It is used to handle buffered input streams.
BufferedWriter: This is used to handle buffered output streams.
InputStreamReader: This input stream is used to translate the byte to the character.
OutputStreamReader: This output stream is used to translate characters to bytes.
PrintWriter: This contains the most used print() and println() methods.
STANDARD I/O STREAMS
Java supports standard I/O like C/C++, with three streams: [Link] (input), [Link] (output) and
[Link] (error).
6
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 [Link].
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 [Link].
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 [Link].
JAVA IO READER AND WRITER
Unlike byte-based streams, Reader and Writer handle character-based I/O, converting between bytes and
characters according to encoding. [Link] and [Link] are abstract superclasses with
subclasses for managing different character sets. Java provides 9 reader and 8 writer classes in the [Link]
package.
Java IO Reader
Reader class is an abstract class for reading character-based data. Subclasses must implement read(char[],
int, int) and close() and often override other methods for efficiency or added functionality.
Different classes of Java IO Reader
7
BufferedReader: Java BufferedReader class is used to record the information from a
character-based input stream.
CharArrayReader: The CharArrayReader class is used to read the character array as a
reader (stream). It inherits Reader class.
FilterReader: Java FilterReader is used to perform filtering operations on the reader
stream.
InputStreamReader: An InputStreamReader class is a bridge from byte streams to
character streams.
LineNumberReader: The LineNumberReaser class keeps track of line numbers of the read
characters. Line numbering begins at 0.
PushbackReader: Java PushbackReader class is a character stream reader. It is used to
pushes back a character into the stream.
PipedReader: The PipedReader class is utilized to read the data of a pipe in the form of a
stream of characters.
StringReader: Java StringReader class is a stream of characters with string as an origin. It
takes an input string and changes it into a character stream.
Java IO Writer
Writer class is an abstract class for writing character streams. Subclasses must implement write(char[],
int, int), flush() and close() and often override other methods for efficiency or added functionality.
Different classes of Java IO Writer
The list of different classes of Java IO Writer is given below -
8
BufferedWriter: Java BufferedWriter class is used to implement buffering for the instances of the
Writer class.
CharArrayWriter: The CharArrayWriter class can be used to write common data to multiple files.
This class inherits the Writer class.
FileWriter: Java FileWriter class is applied to write data to a file that is character-oriented.
OutputStreamWriter: OutputStreamWriter is a class used to transform the character streams to the
byte stream.
PipedWriter: The PipedWriter class is used to write a stream of characters in the form of a java
pipe. This class is generally used for writing text.
PrintWriter: Java PrintWriter class can be described as an implementation of the Writer class.
StringWriter: Java StringWriter class is used to collect the output from a string buffer, which can
be utilized to build a string.
JAVA IO FILE
The Java IO File represents a file or directory path. Since file and directory structures vary across
platforms, File provides a platform-independent way to handle them. It allows operations such as
creating, deleting, renaming files/directories, listing contents and managing file properties.
Characteristics of Java IO File
Represents files and directory pathnames.
Pathnames can be absolute or relative.
Objects are created by providing a filename or directory name.
File access is controlled by permissions (read/write/execute).
File instances are immutable; their pathnames cannot change after creation.
SCANNER CLASS IN JAVA
In Java, the Scanner class is present in the [Link] package is used to obtain input for primitive types
like int, double, etc., and strings. We can use this class to read input from a user or a file. In this article,
we cover how to take different input values from the user using the Scanner class.
Example 1: Taking input from the user using the Scanner class and displaying the output.
// Java program to demonstrate the use of Scanner class
// to take input from user
import [Link];
class Geeks
9
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name:");
String name = [Link]();
[Link]("Hello, " + name + " Welcome to the GeeksforGeeks.");
}
}
OUTPUT:
Explanation: In the above code example, we use the nextLine() of Scanner class to read the line value
which is entered by the user and print it in the console.
Steps To Use Scanner Class to Take Input
Step 1: First, import the [Link] package in top of the program file Without importing this
package, we can not use the Scanner class. either we can import the [Link].* by importing this package
we can use all the classes present in the util package.
import [Link]
public class Geeks{
public static void main(String [] args){
}
}
Step 2: Create the object of the Scanner class.
Scanner sc = new Scanner ([Link]);
Here "sc" is an object of the Scanner class. We can give it different names for our ease such as in, var or
obj etc. Using this object we can use the methods of the Scanner class.
10
Step 3: Create a variable and using scanner class object call the corresponding method to take the
input value.
int age = [Link]();
Java Scanner Input Types
The scanner class helps take the standard input stream in Java. So, we need some methods to extract data
from the stream. The methods used for extracting data are mentioned below:
Method Description
nextBoolean() Used for reading Boolean value
nextByte() Used for reading Byte value
nextDouble() Used for reading Double value
nextFloat() Used for reading Float value
nextInt() Used for reading Int value
nextLine() Used for reading Line value
nextLong() Used for reading Long value
nextShort() Used for reading Short value
11