Java Reference
In-Depth Information
We will use the compact form of reading the data from an input stream in subsequent examples. You need to
place the code for reading data from an input stream in a try - catch block because it may throw an IOException .
Closing the Input Steam
Finally, you need to close the input stream using its close() method.
// Close the input stream
fin.close();
The close() method may throw an IOException , and because of that, you need to enclose this call inside a
try-catch block.
try {
// Close the input stream
fin.close();
}
catch (IOException e) {
e.printStackTrace();
}
Typically, you construct an input stream inside a try block and close it in a finally block to make sure it is
always closed after you are done with it.
All input/output streams are auto closeable. You can use a try-with-resources to create their instances, so they
will be closed automatically regardless of an exception being thrown or not, avoiding the need to call their close()
method explicitly. The following snippet of code shows using a try-with-resources to create a file input stream:
String srcFile = "luci1.txt";
try (FileInputStream fin = new FileInputStream(srcFile)) {
// Use fin to read data from the file here
}
catch (FileNotFoundException e) {
// Handle the exception here
}
A Utility Class
You will frequently need to perform things such as closing an input/output stream and printing a message on the
standard output when a file is not found, etc. Listing 7-14 contains the code for a FileUtil class that you will use in
the example programs.
Listing 7-14. A Utility Class Containing Convenience Methods to Work with I/O Classes
// FileUtil.java
package com.jdojo.io;
import java.io.Closeable;
import java.io.IOException;
public class FileUtil {
// Prints the location details of a file
 
Search WWH ::




Custom Search