How do I read a String from a File?
Author: Deron Eriksson
Description: This Java tutorial describes how to read a String from a File.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page: < 1 2

(Continued from page 1)

You may wonder why the

stringBuffer.append(charArray, 0, numCharsRead);

is required rather than just

stringBuffer.append(charArray);

Let's see what happens if we replace the first line with the second line. The results are shown below.

Execution of incorrectly modified ReadStringFromFile1

As you can see, the problem with that line that we changed is that now the whole character array (of 1024 characters) gets written to the StringBuffer object each time an iteration of the while loop occurs. This even happens on the last iteration, where the number of characters read in the last chunk is a lot less than 1024.

Hopefully this has provided you with an easy way to convert a File to a String, and has shown you one of the potential pitfalls that you can run into when working on File I/O.

Page: < 1 2