Java – Files I/O6 min read

Java Input/Output is used for processing input and giving out output. The package java.io contains all the required classes needed for input/output operation. Java uses the term stream for the representation of I/O operation.

Stream

A stream is a sequence of data. A stream supports many data such as primitives, objects, localized characters, objects, etc. Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream, Reader, and Writer.

The two types of stream, we will be looking at are:

  • Byte Stream
  • Character Stream

Byte stream :

The byte stream classes provide a convenient means for handling byte-oriented I/O. The byte stream classes are topped by InputStream and OutputStream among many other classes.

InputStream:

InputStream is an abstract class that defines Java’s model of streaming byte input. It implements the Closeable interface.

Some of the methods defined by InputStream are:

  • int available():
    Returns the number of bytes of input currently available for reading.
  • void close():
    Closes the input source. Further read attempts will generate an IOException.
  • void mark(int numBytes):
    Places a mark at the current point in the input stream that will remain valid until numBytes bytes are ready.
  • int read():
    Returns an integer representation of the next available byte of input. –1 is returned when the end of the file is encountered.
  • int read(byte buffer[], int offset, int numBytes):
    Attempts to read up to numBytes bytes into the buffer starting at buffer [ offset ], returning the number of bytes successfully read. –1 is returned when the end of the file is encountered.
  • void reset():
    Resets the input pointer to the previously set mark.

OutputStream:

OutputStream is an abstract class that defines streaming byte output. It implements the Closeable and Flushable interfaces.

Some of the methods defined by OutputStream:

  • void close():
    Closes the output stream.
  • void flush():
    Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.
  • void write(byte buffer[]):
    Writes a complete array of bytes to an output stream.
  • void write(int b):
    Writes a single byte to an output stream.

FileInputStream:

The File InputStream class creates an InputStream that you can use to read bytes from a file. These streams of raw bytes include image data, audio, video, etc.

FileOutputStream:

FileOutputStream creates an OutputStream that you can use to write bytes to a file.


Character Stream:

These streams are used to perform for a 16-bit Unicode. It provides a convenient means for handling the input and output of characters. At the top of the character stream hierarchies are the Reader and Writer abstract classes.

Reader:

Reader is an abstract class that defines Java’s model for reading character stream. It implements the Closeable(close()) and Readable (read(char[], int, int)) interfaces. All of the methods in this class will throw an IOException on error conditions.

Some of the methods defined by Reader:

  • abstract void close():
    Closes the input source.
  • void mark(int numChars):
    Places a mark at the current point in the input stream that will remain valid until numChars characters are read.
  • boolean markSupported():
    Returns true if mark()/reset() are supported on this stream.
  • int read():
    Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered.
  • int read(char buffer[]):
    Attempts to read up to buffer. length characters into buffer and returns the actual number of characters that were successfully read. –1 is returned when the end of the file is encountered.
  • boolean ready()
    Returns true if the next input request will not wait. Otherwise, it returns false.
  • void reset():
    Resets the input pointer to the previously set mark.

Writer:

Writer is an abstract class that defines Java’s model for writing character stream. It implementsthe Closeable(close()), Flushable(flush()) and Appendable(char[], int, int) interfaces.

Some of the methods defined by Writer:

  • Writer append(char c):
    Appends c to the end of the invoking output stream. Returns a reference to the invoking stream.
  • abstract void close():
    Closes the output stream.
  • abstract void flush():
    Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.
  • void write(int ch):
    Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered. Writes a single character to the invoking output stream.
  • Writer append(CharSequence chars):
    Appends chars to the end of the invoking output stream. Returns a reference to the invoking stream.

FileReader:

For the reading purposes present on the file, the FileReader creates a class call Reader. It returns data in byte format like FileInputStream class.

Two commonly used constructor in FileReader are

  • FileReader(String filePath)
  • FileReader(File fileObj)

Methods used in FileReader:

  • int read(): return a character in ASCII form, returns -1 at the end of file.
  • void close(): close the FileReader class.

Example: Java program for File I/O.

The following example is to read lines and print these to the standard output stream from a file. The source file must be in the current directory.

We have the following text in “fileTest.txt“:

Welcome to Simple 2 Code

Output:

Welcome to Simple 2 Code


FileWriter:

For the writing purposes present on the file, the FileWriter creates a class call Reader. It returns data in byte format like FileOutputStream class.

Four commonly used constructors in FileWriter are:

  • FileWriter(String filePath)
  • FileWriter(String filePath, boolean append)
  • FileWriter(File fileObj)
  • FileWriter(File fileObj, boolean append)

Methods used in FileWriter:

  • void write(String text): to write the string into FileWriter.
  • void write(char c): to write the char into FileWriter.
  • void write(char[] c): to write char array into FileWriter.
  • void flush(): to flushes the data of FileWriters.
  • void close(): to close the FileWriter.

Example: Java program for File I/O.

The following example is to write lines and print these to the standard output stream from a file. The source file must be in the current directory.

Output:

Done

Now check the text file, “WriterTest.txt” in the same directory.

Welcome to Simple2Code.

Example: Use of BufferReader in Java


MORE

Java Program to find the sum of the Largest Forward Diagonal

in this tutorial, we will write a java program to find the sum of the Largest Forward Diagonal in an Arraylist (matrix). Java Program to …

C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a number using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …