Table of contents
1.
Introduction
2.
Stream
2.1.
Byte Streams
2.2.
Character Streams
2.3.
Standard Streams
3.
Reading and Writing Files
3.1.
FileInputStream
3.1.1.
Example
3.2.
Java
3.3.
Useful methods of InputStream
3.4.
InputStream Hierarchy
3.5.
FileOutputStream
3.5.1.
Example
3.6.
Java
3.7.
Useful methods of OutputStream
3.8.
OutputStream Hierarchy
4.
Frequently Asked Questi
4.1.
What is the application of FileReader in Java? 
4.2.
What is the use of PrintWriter class? 
4.3.
How to get the input from a file in Java?
5.
Conclusion
Last Updated: Apr 20, 2024
Easy

File Input/Output

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The java.io package contains nearly all the packages needed to perform Java's input and output operation. These streams must always represent an input source and an output destination.
Java I/O(Input and Output) takes input and generates the output. With the help of streams in Java, it makes the I/O execution faster. This java.io package consists of all the required classes to create input and output operations.

​​File Input/Output

Recommended Topic, Sum of Digits in C, Duck Number in Java

Stream

As the stream suggests, it is a sequence of data. In Java, a stream is consists of bytes. This is termed the stream because it is like a stream of water that continues to flow.

In Java, there are three streams created for us automatically. All of these are attached to the console.

1.System.out: the standard output stream

System.out.println(“simple message”);

 

2. System.in: the standard input stream

int i = System.in.read();
System.out. println((char)i);

 

3. System.err: the standard error stream

System.err.println(“error message”);

Byte Streams

It is a byte stream used to perform input and output of 8-bit bytes. The most used classes are, FileInputStream and FileOutputStream. 

Syntax

ByteArrayInputStream inputStream = new ByteArrayInputStream();

Character Streams

Java Character streams help us perform input and output on a 16 bit Unicode. Many classes are related to character streams, but the most commonly used are FileReader and FileWriter. Though both of these internally use FileReader as FileInputStream and FileWriter and FileOutputStream. There is also a prime difference between these two types FileReader reads two bytes at a time, and FileWriter writes two bytes.

Syntax

File file = new File("input.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()]

Here FileReader is a method of Character Stream class.

Standard Streams

Standard Streams are used to generate standard input and output messages. Java provides three traditional streams:

  1. Standard Input: A keyboard is generally required to input the data to the user's program, and it has represented as System.in.
  2. Standard Output: This is used to generate the output data produced by the user's program. The output is usually represented as System.out.
  3. Standard Error: This is used to generate the error data produced by the user's program. This is represented as System.err.

Also see, Hashcode Method in Java and  Swap Function in Java

Reading and Writing Files

As explained earlier, a stream can be expressed as a data sequence. The InputStream helps us read the data from the files, and the OutputStream is used to print the data from the file.

FileInputStream

This stream is used to read the data from the files. With the help of a new keyword, objects can be created. Here is the example of reading the file

InputStream isr = new FileInputStream(“C:/JavaCode/hello”);

Another example is to create an object first and then read the file.

File fl = new File(“C:/JavaCode/hello”);
InputStream f = new FileInputStream(fl);

Example

  • Java

Java

import java.io.*;
public class FileInput1
{
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
try
{
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
}
while(c != 'q');
}
finally
{
if (cin != null)
{
cin.close();
}
}
}
}
You can also try this code with Online Java Compiler
Run Code

Output

Enter characters, 'q' to quit.
q
q

In this example, we have taken the input from the user. After taking some information, we have manipulated it according to the user's need. We used in InputStreamReader to input some characters from the user. After entering the character, we check for certain conditions if that character is equal to the given or not; otherwise, it will keep on iterating till it satisfies the requirement.

Useful methods of InputStream

In Java, the InputStream class provides a way to read data from a source in a byte-oriented manner. Some useful methods of the InputStream class include:

  • read(): Reads the next byte of data from the input stream and returns it as an integer value.
  • read(byte[] b): Reads some number of bytes from the input stream and stores them into the buffer array b.
  • available(): Returns an estimate of the number of bytes that can be read from the input stream without blocking.
  • close(): Closes the input stream and releases any system resources associated with it.

These methods allow for efficient reading of data from various input sources such as files, network sockets, and in-memory byte arrays.

InputStream Hierarchy

In Java, the InputStream class is an abstract base class for all classes representing input streams. It is part of the Java I/O (Input/Output) API. The InputStream class is located in the java.io package.

The InputStream hierarchy includes various subclasses that provide different ways of reading data from input sources. Some common subclasses of InputStream include:

  • FileInputStream: Reads data from a file in the file system.
  • ByteArrayInputStream: Reads data from an in-memory byte array.
  • FilterInputStream: Provides a base class for input stream classes that filter bytes as they are read from another input stream.
  • BufferedInputStream: Adds buffering functionality to an input stream, improving performance by reducing the number of calls to the underlying input stream.

FileOutputStream

The FileOutputStream is used to create a file and write the data. This stream would create a file and, if it already doesn’t exist, before opening it for the output. Here is the example

OutputStream os = new FileOutputStream(“C:/JavaCode/hello”);

Another example of FileOutputStream

File f = new File(“C:/JavaCode/hello”);
OutputStream os = new FileOutputStream(os);

Example

  • Java

Java

import java.io.*;
public class FileOutput1
{
public static void main(String[] args) throws IOException
{
File file = new File("D:/Java/input.txt");
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
if(file.exists()) {
System.out.println("Filename: "+ file.getName());
System.out.println("Absolute path:"+ file.getAbsolutePath());
System.out.println("File size in bytes "+ file.length());
System.out.println("Executable "+ file.canExecute());
System.out.println("Readable "+ file.canRead());
System.out.println("Writeable "+ file.canWrite());
System.out.close();
}
}
}
You can also try this code with Online Java Compiler
Run Code

Output

Filename: input.txt
Absolute path: D:\Java\input.txt
File size in bytes 181
Executable true
Readable true
Writeable true

In this example, we have created a file and then have some content. We used some methods which are present in file handling. 

Useful methods of OutputStream

In Java, the OutputStream class provides a way to write data to a destination in a byte-oriented manner. Some useful methods of the OutputStream class include:

  • write(int b): Writes the specified byte to the output stream.
  • write(byte[] b): Writes b.length bytes from the specified byte array to the output stream.
  • flush(): Flushes the output stream, ensuring that any buffered data is written to the underlying output destination.
  • close(): Closes the output stream and releases any system resources associated with it.

These methods allow for efficient writing of data to various output destinations such as files, network sockets, and in-memory byte arrays.

OutputStream Hierarchy

In Java, the OutputStream class is an abstract base class for all classes representing output streams. It is part of the Java I/O (Input/Output) API and is located in the java.io package.

The OutputStream hierarchy includes various subclasses that provide different ways of writing data to output destinations. Some common subclasses of OutputStream include:

  • FileOutputStream: Writes data to a file in the file system.
  • ByteArrayOutputStream: Writes data to an in-memory byte array.
  • FilterOutputStream: Provides a base class for output stream classes that filter bytes as they are written to another output stream.
  • BufferedOutputStream: Adds buffering functionality to an output stream, improving performance by reducing the number of calls to the underlying output stream.

Try it on online java compiler.

Frequently Asked Questi

What is the application of FileReader in Java? 

File reader can read the entire file's contents in one go. The constructor of FileReader can accept the file(File) or the absolute path to the file as an argument.

What is the use of PrintWriter class? 

The PrintWriter provides advanced methods to make formatted text to the file. This class also supports the printf function. PrintWriter constructors support various kinds of arguments.

How to get the input from a file in Java?

To get input from a file in Java, you can use the FileInputStream class along with the InputStreamReader and BufferedReader classes for efficient reading.

Conclusion

In this article, we take a look at file input-output. We took a brief introduction about Java I/O. We then also moved on to what streams are and their different types. We also discussed Reading and Writing Files and their types. We also discussed a few examples related to the above topics.

If you want to explore more about such topics, please visit our website, Programming Fundamentals.

Live masterclass