2012-03-24 11 views
5

行単位ではなく、一度にString型にBufferedReaderを配置する方法はありますか?ここで私はこれまで持っているものです。どのようにして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); 

答えて

5

同じライブラリにApache FileUtilsライブラリを使用できます。

1

あなたの入力の長さ(またはそれに上限を)知っている場合は、read(char[],int,int)を使用して、文字配列に全部を読むことができ、その後、構築するためにそれを使用文字列。 3番目のパラメータ(len)がサイズより大きい場合、メソッドは読み込まれた文字数を返します。

+0

サイズが何であるか分かりません。実際にはどんなサイズでもかまいません。回答ありがとうございました。 – BigBug

+1

これは実際には他のライブラリを使用しないと最適なソリューションです。 APIから: "基本ストリームの' first read'がファイルの終わりを示す-1を返した場合、このメソッドは '-1'を返します。そうでなければ、実際に読み取られた文字数を返します。使用方法は次のとおりです。http://pastebin.com/RvGwKLuC – bezmax

+0

もう少し説明すると、BufferedReaderは他のリーダーを囲んでいます。 'read(char []、int、int)'を呼び出すと、それはそのバッファに基本リーダーの 'read():int'への順次呼び出しでいっぱいになります。内部バッファがいっぱいになると、内部バッファの一部が取得され、指定された配列に挿入されます。つまり、APIの中には、それらの読み込み呼び出しのうちの最初のものが '-1'を返すと、このメソッドはストリームの終わりであるので、' -1'も返します。それ以外の場合(例えば、1回の読み込み呼び出しが成功し、2回目に '-1'が返された場合)、読み込まれた文字数が返されます。 – bezmax

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(); 
関連する問題