Fileinputstream java io ioexception read error

Class FileInputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .

Constructor Summary

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

Creates a FileInputStream by using the file descriptor fdObj , which represents an existing connection to an actual file in the file system.

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

Method Summary

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream .

Methods declared in class java.io.InputStream

Methods declared in class java.lang.Object

Constructor Details

FileInputStream

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkRead method is called with the name argument as its argument. If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

Читайте также:  Определить площадь круга python

FileInputStream

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkRead method is called with the path represented by the file argument as its argument. If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

FileInputStream

Creates a FileInputStream by using the file descriptor fdObj , which represents an existing connection to an actual file in the file system. If there is a security manager, its checkRead method is called with the file descriptor fdObj as its argument to see if it’s ok to read the file descriptor. If read access is denied to the file descriptor a SecurityException is thrown. If fdObj is null then a NullPointerException is thrown. This constructor does not throw an exception if fdObj is invalid . However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.

Method Details

read

read

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

read

Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

skip

Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0 . If n is negative, the method will try to skip backwards. In case the backing file does not support backward skip at its current position, an IOException is thrown. The actual number of bytes skipped is returned. If it skips forwards, it returns a positive value. If it skips backwards, it returns a negative value. This method may skip more bytes than what are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file.

available

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. Returns 0 when the file position is beyond EOF. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.

close

Closes this file input stream and releases any system resources associated with the stream. If this stream has an associated channel then the channel is closed as well.

getFD

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream .

getChannel

Returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file so far. Reading bytes from this stream will increment the channel’s position. Changing the channel’s position, either explicitly or by reading, will change this stream’s file position.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

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

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:

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

java.io.ioexception - Sequence Diagram

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

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

java.io.ioexception

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.

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

java.io.ioexception - EOFException

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

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

FileNotFoundException

The output of the code when executed is shown below.

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

Источник

Оцените статью