Java Reference
In-Depth Information
As an example, the following code fragment shows how to loop over the contents of a directory
using the legacy API:
import java.io.File;
public class ShowDirectory {
public static void main(String[] args) {
File folder = new File("C:\\");
for (File entry : folder.listFiles()) {
System.out.println(entry.getName());
}
}
}
This particular example might appear simple compared to the corresponding NIO2 implementation
(fewer imports are used), but keep in mind the other advantages of NIO2 (reading and writing, for
instance). The NIO2 approach remains the recommended one.
a Word on FileUtils
Java's file input/output classes—and the legacy ones in particular—miss some widely used features
that are both somewhat annoying and time consuming to implement yourself, or require a great
amount of exception juggling to implement gracefully. You've already seen an example of this in the
form of the implementation of copy, move, and delete operations for whole directories.
When you're looking for an implementation to properly copy, clean, and move directories or per-
form many other common file operations, the FileUtils utility class by the Apache Commons
project is worth looking at. In fact, many programmers consider this class so helpful and so essential
that they will include it as a library in any new Java project they set up. Take a look at the follow-
ing website if you're interested in knowing more or want to download and use the library (add it to
Eclipse's build path in order to use it): http://commons.apache.org/proper/commons-io/ .
One downside of the FileUtils library, however, is that it is built with Java 6 compatibility in
mind, meaning that the legacy File class is used in its method arguments, without Path and Files
being present. If you use the FileUtils library, consider using the previously discussed Path.
toFile() method to keep the rest of your code base NIO-ready.
conclusion
This concludes this chapter on basic input/output with Java and file input/output. You've seen what
is meant by stream-based input/output, learned how to interact with users over the command-line,
and learned how to write and read content to and from files, using both the NIO2 and legacy API.
As always, don't be afraid to peruse the Java docs or explore the methods offered by Path and Files
and other classes using Eclipse's autosuggest functionality. It is a great way to experiment and learn.
This chapter was largely about saving and reading data to and from files. The next chapter intro-
duces databases, a more advanced and powerful method to store and retrieve information.
 
Search WWH ::




Custom Search