Java error reading file are the common error occurred in java that when
the user encounter a corrupt file and show a message to the user reason for the
failure.
Understand with Example
In this Tutorial we help you in understanding a n example from Java error
reading from file. For this we have a class error reading from file. Inside the
main method we have a try block that create an instance of
errorreadingfromfile.
1).readfile ( ) -This method is used to read a file.
Try block subsequently followed by a catch block that is used to catch
exception
We have a readline method that include try block declares a variable
String name text is initialized with null.
1)Fileinputstream-The Fileinputstream is used to decode the byte and
convert it into character type.
2)Bufferedinput stream-The Bufferedinputstream is used to read the character
from the given text file.
3)Datainputstream -The Datainputstream allow the
application to read from primitive data type from underlying input stream.
4)close (
)
-This close the filestream.
While evaluate the text, if it is not null, The System.out.println print the text,
Otherewise,it move to the catch block to show user defined message" An error
occur while reading file".
errorreadingfromfile.java
import java.io.*;
public class errorreadingfromfile {
public static void main(String[] args) throws Exception {
try {
errorreadingfromfile f = new errorreadingfromfile();
f.readfile();
} catch (Exception e) {
System.out.println(e);
}
}
void readfile() {
try {
String text = null;
File file = new File("/home/girish/Desktop/g.txt");
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new
BufferedInputStream(fileInputStream);
DataInputStream dis = new DataInputStream(bufferedInputStream);
fileInputStream.close();
while ((text = dis.readLine()) != null) {
System.out.println(text);
}
} catch (Exception ex) {
System.out.println("An Error occurs while reading file");
}
}
}
|
Output
Compiling 1 source file to /home/girish/NetBeansProjects/errors/build/classes
Note: /home/girish/NetBeansProjects/errors/src/
errorreadingfromfile.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
compile-single:
run-single:
An Error occurs while reading file
BUILD SUCCESSFUL (total time: 0 seconds)
|
Download code