Text and Binary Files
File input and output
I/O exceptions
A subset of the IOException hierarchy
IOException
EOFException
FileNotFoundException
Common I/O exceptions
| Exception | Description |
|---|---|
| IOException | Thrown when an error occurs in I/O processing. |
| EOFException | Thrown when a program attempts to read beyond the end of a file. |
| FileNotFoundException | Thrown when a program attempts to open a file that doesn't exist. |
Code that handles I/O exceptions
BufferedReader in = null;
try
{
if (productsFile.exists()) // prevent the FileNotFoundException
{
in = new BufferedReader(
new FileReader(productsFile));
String line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
}
else
System.out.println(productsFile.getPath()
+ " doesn't exist");
}
catch(IOException ioe) // catch any other IOExceptions
{
System.out.println(ioe);
}
finally // close the stream even if an exception was thrown
{
this.close(in); // call the close method
}
A method that closes a stream
private void close(Closeable stream)
{
try
{
if (stream != null) // prevent a NullPointerException
stream.close();
}
catch(IOException ioe)
{
System.out.println("Unable to close stream: " + ioe);
}
}