Java Cookbook, Second Edition

Problem

You need to read the entire contents of a file into a string.

Solution

Use my FileIO.readerToString( ) method.

Discussion

This is not a common activity in Java, but sometimes you really want to do it. For example, you might want to load a file into a "text area" in a GUI. Or process an entire file looking for multiline regular expressions (as in Recipe Recipe 4.11). Even though there's nothing in the standard API to do this, it's still easy to accomplish with the readerToString( ) method in com.darwinsys.util.FileIO, the source for which is included and discussed in Recipe 10.7. You just say something like the following:

Reader is = new FileReader(theFileName); String input = FileIO.readerToString(is);

Категории