如何将BufferedReader的内容放入String中?

5
有没有一种方法可以将BufferedReader一次性放入一个字符串中,而不是逐行读取?以下是我目前的做法:
            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个回答

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

5

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

我完全不知道它的大小,它可能是任何大小...无论如何,感谢您的回复。 - BigBug
1
这实际上是不使用其他库的最佳解决方案。从 API 中可以看到:“如果底层流的第一次读取返回 -1,表示已达到文件结尾,则此方法返回 -1。否则,此方法返回实际读取的字符数。” 这是如何使用它的示例:http://pastebin.com/RvGwKLuC - bezmax
进一步解释一下:BufferedReader 包装了其他的 reader。当你调用 read(char[],int,int) 时,它会通过对底层 reader 的连续调用 read():int 来填充它的缓冲区。当内部缓冲区被填满时,它会将其中一部分插入到给定的数组中。因此,API 表示,如果这些底层 read 调用中的第一个返回 -1,那么该方法也会返回 -1,因为它是流的结尾。否则(例如,如果第一次读取调用成功,第二次返回 -1),它仍然会返回已读取的字符数。 - bezmax
@Max 谢谢澄清。我已经有一段时间没有使用过这个功能了,我真的记得它是以那种方式工作的。但是当我重新阅读文档以确保时,最终却误解了它... - mgibsonbr

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接