• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

read from a file into a string

 
tarun Mehra
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
------------------
 
tarun Mehra
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
Tarun
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure you can. You have to write it yourself, but it's not too hard. Here's a quick solution:
<code><pre>
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 = reader.read(cbuf)) >= 0) {
sb.append(cbuf, 0, num);
}
return sb.toString();
}
</pre></code>
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic