How do you put the contents of a BufferedReader in a String?

Is there a way to put a BufferedReader in a String with one shot, rather than row by row? Here is what I still have:

            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); 
+5
source share
4 answers

You can use the Apache FileUtils library for this.

+5
source

Using the methods StringBuilderand read(char[], int, int)will look like, and probably this is the best way to do this 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();
+5
source

( ), , read(char[],int,int), , String. , (len) , .

+1

All Articles