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

1 comment:

  1. Casinos in New Jersey, Nevada, Louisiana, Arkansas, and South Dakota now provide multi-state progressive jackpots, which now provide larger jackpot swimming pools. A slot machine's theoretical payout share is ready on the manufacturing unit when the software program is written. A theoretical hold worksheet is a document supplied by the manufacturer for each slot machine that signifies the theoretical share the machine ought to hold based on the quantity paid in. The 우리카지노 worksheet additionally signifies the reel strip settings, number of coins could be|that could be|which may be} played, the payout schedule, the number of reels and other info descriptive of the particular sort of slot machine. Free spins are a standard form of bonus, where a collection of spins are mechanically played at no charge on the participant's present wager.

    ReplyDelete