File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes read from a file into a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "read from a file into a string" Watch "read from a file into a string" New topic

read from a file into a string

tarun Mehra

Joined: May 30, 2001
Posts: 12
I want to capture the entire content of a file into a single string. Is there a way to do it without doing it line by line through buffered reader's readLine() method. The readLine() method affects the performance considerably.
Thank you,
tarun Mehra

Joined: May 30, 2001
Posts: 12
hi everybody,
Can anyone tell me if this is possible. That is instead of capturing the string line by line, capture it all at once.
Thank you,
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Sure you can. You have to write it yourself, but it's not too hard. Here's a quick solution:
public static String toString(File file) throws IOException {
StringBuffer sb = new StringBuffer();
Reader reader = new FileInputStream(file);
char[] cbuf = new char[1024];
int num;
while ((num = >= 0) {
sb.append(cbuf, 0, num);
return sb.toString();
You can experiment with tuning the size of the cbuf array. Also it may be worthwhile to estimate the maximum size needed for the StringBuffer, and use that as the initial size. The main optimizations of this method over a readLine() solution are: we're not creating a new String object for each line, and we're not forcing the JVM to scan every character read just to see if it's an end of a line. Other than that, the system is still going to have to read every character of the file; I think this is about as fast as you're going to get. Note that I'm pretty sure it's redundant (and therefore slightly slower) to use a BufferedReader here, since we've already got a character buffer in the system, but you can test this yourself.
[This message has been edited by Jim Yingst (edited July 12, 2001).]

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: read from a file into a string
It's not a secret anymore!