Wednesday, March 27, 2013

Reading whole file into a String

Reading a text file into a String object is a useful operation in many areas. For example, it can be used in text editor, syntax highlighter, "find and replace" tools and grep application.

Memory Constraints

For typical cases, most of the text files are less than 1MB in size. With today memory capacity, it is not a concern. However, we may still wish to limit the file size to avoid the user from using a 4GB movie file as input. Therefore, the first step in reading the whole file is to check the file size.

Getting the file size

The file size of a file can be read by the following code: where fileName is just a String containing the name of file, e.g. "a.txt".

Limiting the file size

I have arbitrarily chosen a file size limit of a million bytes, change it to what you need.

Buffer Allocation

Now we have the file size. It is convenient to allocate a buffer to hold the whole file.

Using DataInputStream for reading

The next step is to create a DataInputStream for reading the file.

Read the whole file into String

Now everything is ready and we may read the whole file into the byte array, and the create a String object from it.

Putting it all together

Related Posts

No comments:

Post a Comment