IOException

java.io.IOException – How to solve Java IOException

In this article, we will explain how to solve the java.io.IOException.

This exception is related to Input and Output operations in the Java code. It happens when there is a failure during reading, writing, and searching file or directory operations. IOException is a checked exception. A checked exception is handled in the java code by the developer. This exception object has a string message which is the root cause for the failure.

IOException has subclasses such as FileNotFoundException, EOFException, UnsupportedEncodingException, SocketException, and SSLException. If the file is not found, FileNotFoundException is thrown. While reading a file, EOFException occurs when the end of the file is reached. If the file has an unsupported encoding, UnsupportedEncodingException occurs. When the socket connection is closed, SocketException can happen. SSLException happens when the SSL connection is not established.

java.io.ioexception - IOException
IOException Subclasses

1. Prerequisites

Java 7 or 8 is required on the Linux, windows, or Mac operating system.

2. Download

You can download Java 7 from the Oracle site. On the other hand, You can use Java 8. Java 8 can be downloaded from the Oracle website.

3. Setup

You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:

Setup

JAVA_HOME="/desktop/jdk1.8.0_73"
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

4. What is Java IOException – java.io.IOException

java.io.IOException is an exception which programmers use in the code to throw a failure in Input & Output operations. It is a checked exception. The programmer needs to subclass the IOException and should throw the IOException subclass based on the context.

5. UML diagram

The sequence diagram of throwing the IOException in classes Manager, Service, Facade, and Persistence Manager is shown below:

java.io.ioexception - Sequence Diagram
IO Exception Sequence Diagram

6. When is IOException thrown 

Java application needs to handle failures related to reading, writing, and searching a file or a directory. java.io.IOException is the base exception class used for handling the failures. In a method of a class, try, catch, and finally block handles the exception. The application API class methods throw an IOException or its subclasses.

Try catch finally block of code is shown below in different scenarios. The code below shows the printing of the exception stack trace.

Printing Stack trace

try
{
   
}
catch(IOException ioException)
{
    ioException.printStacktrace();
}
finally
{
}

In the code below, a runtime exception is thrown after catching the IOException in a java application.

throwing a runtime exception

try
{
   
}
catch(IOException ioException)
{
    throw new RuntimeException("IO Exception in CommandLine Application",ioException);
}
finally
{
}

In the code below, a wrapped exception is thrown after catching IOException in Facade class.

throwing a wrapped exception

try
{
   
}
catch(IOException ioException)
{
    throw new WrappedException("IO Exception in Facade" ,ioException);
}
finally
{
}

In the code below, throwing a business exception after catching the IOException is shown.

Throwing a business exception

try
{
   
}
catch(IOException ioException)
{
    throw new BusinessException("IO Exception in Service" ,ioException);
}
finally
{
}

Throwing an application exception after catching an IOException is presented in the code below:

Throwing an application exception

try
{
   
}
catch(IOException ioException)
{
    throw new ApplicationException("IO Exception in Manager" ,ioException);
}
finally
{
}

6. A simple case of java.io.ioexception

Let’s see a very simple case of a Java IOException. In the following example, we are going to try to read some lines of text from a file that does not exist:

IOException

import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionExample
{
    public void checkFileNotFound()
    {
        try 
        {
            FileInputStream in = new FileInputStream("input.txt");
            System.out.println("This is not printed");
        } 
        catch (FileNotFoundException fileNotFoundException)
        {
            fileNotFoundException.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
		FileNotFoundExceptionExample example = new FileNotFoundExceptionExample();
		example.checkFileNotFound();
	}
}

The code above is executed as shown below:

Run Command

javac InputOutputExceptionExample.java
java InputOutputExceptionExample

Now, when you run this program because the file input.txt does not exist, the exception is thrown as shown in the screen below. As you can see the message is showing the cause of the problem. The root cause of the problem is that the file does not exist.

java.io.ioexception
IOException

EOFException is a subclass of the IOException.The code below shows how an EndOfFileException happens while reading an input file. While reading a file, EOFException is thrown when the end of the file is reached.

EndOfFileException

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class EndOfFileExceptionExample 
{
	public void checkEOF()
    {
		File file = new File("einput.txt");
		DataInputStream dataInputStream =  null;
		try
        {
			dataInputStream = new DataInputStream(new FileInputStream(file));
			while(true)
            {
				dataInputStream.readInt();	
			}			
		}
        catch (EOFException eofException)
        {			
			eofException.printStackTrace();
		}
		catch (IOException ioException)
        {
			ioException.printStackTrace();
		}
		finally
        {
			try{
				if (dataInputStream != null)
                {
					dataInputStream.close();
				}
			}
            catch (IOException ioException)
            {
				ioException.printStackTrace();
			}
		}
	}
	public static void main(String[] args)
    {
		EndOfFileExceptionExample example = new EndOfFileExceptionExample();
		example.checkEOF();
	}
}

The code above is executed as shown below:

Run Command

javac EndOfFileExceptionExample.java
java EndOfFileExceptionExample

You can run the above code as per the command above. The output is as shown on the screen below.

java.io.ioexception - EOFException
EOFException

FileNotFoundException is a subclass of IOException. FileNotFoundException scenario is presented in the code below. This happens if the input file is not found.

FileNotFoundException

import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionExample
{
    public void checkFileNotFound()
    {
        try 
        {
            FileInputStream in = new FileInputStream("input.txt");
            System.out.println("This is not printed");
        } 
        catch (FileNotFoundException fileNotFoundException)
        {
            fileNotFoundException.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
		FileNotFoundExceptionExample example = new FileNotFoundExceptionExample();
		example.checkFileNotFound();
	}
}

The code above is executed as shown below:

Run Command

javac FileNotFoundExceptionExample.java
java FileNotFoundExceptionExample

The output of the code when executed is shown below.

FileNotFoundException
FileNotFoundException

7. How to solve java.io.IOException

IOException is a Java exception that occurs when an IO operation fails. Develop can explicitly handle the exception in a try-catch-finally block and print out the root cause of the failure. The developer can take the correct actions to solve this situation by having additional code in the catch and finally blocks.

8. Download the Source Code

That was an example of how to solve the java.io.ioexception.

Download
You can download the full source code of this example here: java.io.ioexception – How to solve Java IOException

Last updated on Oct. 12th, 2021

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button