5

Is there a way to place a BufferedReader into a String in one shot, rather than line by line? Here is what i have so far:

            BufferedReader reader = null;
            try 
            {
                reader = read(filepath);
            } 
            catch (Exception e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                String line = null;
                String feed = null; 
                try 
                {
                    line = reader.readLine();
                } 
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                while (line != null) 
                {
                    //System.out.println(line);
                    try 
                    {
                        line = reader.readLine();
                        feed += line; 
                    } 
                    catch (IOException e) 
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
                }
        System.out.println(feed); 
Brian Willis
  • 22,768
  • 9
  • 46
  • 50
BigBug
  • 6,202
  • 23
  • 87
  • 138

4 Answers4

5

You could use Apache FileUtils library for the same.

A Null Pointer
  • 2,261
  • 3
  • 26
  • 28
5

Using the StringBuilder and read(char[], int, int) methods would look like this, and is probably the most optimal way to do it in Java:

final MAX_BUFFER_SIZE = 256; //Maximal size of the buffer

//StringBuilder is much better in performance when building Strings than using a simple String concatination
StringBuilder result = new StringBuilder(); 
//A new char buffer to store partial data
char[] buffer = new char[MAX_BUFFER_SIZE];
//Variable holding number of characters that were read in one iteration
int readChars;
//Read maximal amount of characters avialable in the stream to our buffer, and if bytes read were >0 - append the result to StringBuilder.
while ((readChars = stream.read(buffer, 0, MAX_BUFFER_SIZE)) > 0) {
    result.append(buffer, 0, readChars);
}
//Convert StringBuilder to String
return result.toString();
bezmax
  • 25,562
  • 10
  • 53
  • 84
1

If you know the length of your input (or an upper bound to it) you can read the whole thing to a character array, using read(char[],int,int), then use that to build a String. It doesn't matter if your third parameter (len) is greater than the size, the method will return the number of characters read.

mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • I'll have no idea what the size is at all, it could be any size really.. thanks for the response anyway.. – BigBug Mar 24 '12 at 05:47
  • 1
    This is actually the best solution without using other libraries. From the API: "If the `first read` on the underlying stream returns -1 to indicate end-of-file then this method `returns -1`. Otherwise this method returns the number of characters actually read." Here's how you use it: http://pastebin.com/RvGwKLuC – bezmax Mar 24 '12 at 06:13
  • To explain a bit further: BufferedReader wraps around some other reader. When you call `read(char[],int,int)` it fills it's buffer with sequential calls to `read():int` of underlying reader. When the inner buffer is filled - it gets a part of it, and inserts into the given array. So the API says, that if FIRST of those underlying read calls returned `-1` - then this method returns `-1` too, as it IS end of the stream. Otherwise (for example, if 1 read call succeeded, and second returned `-1`) - it will still return number of characters that were read. – bezmax Mar 24 '12 at 06:17
  • @Max thanks for the clarification. It's been a while since I last used this, and I really remembered it working that way. But when I re-read the docs just to be sure, I ended up misinterpreting it... – mgibsonbr Mar 24 '12 at 06:33
0

With Guava, CharStreams.toString(reader) does the job.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413