interface, autoboxing, and the foreach loop, InputStream and Reader do not provide iterators that return bytes and chars accordingly. You can fill this gap with two byte-producing iterables: bytes(InputStream is) and bytes(File file). The following is a typical usage of this construction (known in XXth century as the Iterator pattern):
for (byte b : bytes(new File("c:\\windows\zapotec.bmp"))) {
System.out.println(Integer.toHexString(b));
}
You can use similar methods, chars(File file) and chars(Reader reader), to scan through characters in a file:
for (char c : chars(new File("c:\\windows\win.ini"))) {
System.out.println("'"+c+"' (" + Integer.toHexString(c) +")");
}
The two remaining methods, lines(File file) and lines(Reader reader), scan through a text file's lines:
for (String line : lines(new File("c:\\windows\win.ini"))) {
System.out.println(">" + line);
}
Note that these operations have a hidden problem. What happens to the input stream that is open behind the scenes? The private iterator that lists input data does its best to close the stream after it finds no more data there, but other unfortunate events can happen. For instance, an exception can be thrown and control then never returns to the loop. For this occurrence, all these internal iterators implement finalize() where the stream or reader is being closed, unless it was not previously closed. Since the iterables and iterators produced by bytes(), chars(), or lines() are not referenced outside the scope of the for loop, the first garbage collection closes the remaining streams. Note that the code above calls System.gc() after each failed attempt of setLastModified().
Library Sugar
Two methods, install(Class c, String resourceName, File directory) and install(Class c, String resourceName, String directoryName) may be all you need to implement a simple software installer. These methods extract a resource from the application jar (or wherever it is deployed). Expecting the resource to be a zip archive, they unzip the archive and store the content to the specified directory. Often, this is all that an installer needs, is it not?
The Tiger Takeover
Files is just one utility class in MyJavaTools.com project. The other classes in the library are currently being converted to J2SE 5.0. This latest version of Java is gradually gaining popularity, but the Java community may take years to really appreciating all its features.