Java Reference
In-Depth Information
/** Open a BufferedReader from a named file. */
public
public static
static BufferedReader openFile ( String fileName )
throws
throws IOException {
return
return new
new BufferedReader ( new
new FileReader ( fileName ));
}
}
But wait: did you look closely at the body of copyFile(String inName , PrintWriter pw ,
boolean close) ? If you didn't, have a look. You'll notice that I cheated and just delegated
the work to copyFile(Reader is , Writer os , boolean close) . If I'm copying a file from
one place on disk to another, why go through the overhead of converting it from external
form to Unicode and back? Normally, you won't have to. But if you have something like a
network filesystem mounted from Windows to Unix, or vice versa, it's better to do it a line at
a time.
Reading a File into a String
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 Program: Data Mining ). 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 Copying
a File . You just say something like the following:
Reader is = new FileReader(theFileName);
String input = FileIO.readerToString(is);
Search WWH ::




Custom Search