2012-03-24 50 views
5

有沒有辦法將BufferedReader放入一個字符串中而不是一行一行?以下是我迄今爲止:如何將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); 

回答

1

如果你知道你輸入的長度(或上限的話),你可以閱讀整個事情到一個字符數組,使用read(char[],int,int),然後用它來打造一個字符串。無論您的第三個參數(len)是否大於該大小,該方法都會返回讀取的字符數。

+0

我不知道尺寸是什麼,它可以是任何尺寸真的..謝謝你的反應.. – BigBug 2012-03-24 05:47:23

+1

這實際上是最好的解決方案,而不使用其他庫。在API中:「如果基礎流上的第一次讀取返回-1來指示文件結束,那麼此方法返回-1,否則此方法返回實際讀取的字符數。」以下是你如何使用它:http://pastebin.com/RvGwKLuC – bezmax 2012-03-24 06:13:37

+0

進一步解釋一下:BufferedReader包裝了一些其他的讀者。當你調用read(char [],int,int)時,它會連續調用底層讀取器的read():int來填充緩衝區。當內部緩衝區被填充時 - 它得到它的一部分,並插入到給定的數組中。所以API說,如果這些底層讀取調用中的FIRST返回「-1」,那麼此方法也會返回「-1」,因爲它是流的末尾。否則(例如,如果1次讀取調用成功,並且第二次返回'-1') - 它仍然會返回讀取的字符數。 – bezmax 2012-03-24 06:17:03

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(); 
相關問題