如何将BufferedReader的内容放入String?

时间:2012-03-24 05:37:37

标签: java

有没有办法将BufferedReader一次性放入String中,而不是逐行放置?以下是我到目前为止的情况:

            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); 

4 个答案:

答案 0 :(得分:5)

您可以使用Apache FileUtils库。

答案 1 :(得分:5)

使用StringBuilderread(char[], int, int)方法看起来像这样,并且可能是用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();

答案 2 :(得分:1)

如果您知道输入的长度(或它的上限),您可以使用read(char[],int,int)将整个事物读取到字符数组,然后使用它来构建字符串。如果您的第三个参数(len)大于该大小,则该方法将返回读取的字符数。

答案 3 :(得分:0)

使用GuavaCharStreams.toString(reader)完成工作。

相关问题