2014-02-17 150 views
1

此方法沒有返回有效的字符串。可能是什麼原因?存儲在字符串

static BufferedWriter writer = null; 
static int maxlines = 100; 
public static String getTrimmedResponse(BufferedReader b) 
{ 

    try { 

     int count = 0; 
     writer = new BufferedWriter(new StringWriter()); 

     for (String line; (line = b.readLine()) != null;) { 
      if (count++ % maxlines == 0) 


      line = line.replaceAll("\\n", ""); 

      String trimmedLine = line.trim(); 
      if (trimmedLine.charAt(trimmedLine.length() - 1) == '>') 
       writer.append(trimmedLine); 
      else  
      writer.write(line); 
      writer.newLine(); 
     } 



    } catch (IOException e) { 
     e.printStackTrace(); 
     Log.i("texception", e+""); 
    } 
    return writer.toString(); 

}

+2

這將是很難讓你的縮進和代碼塊更加混淆。 – Bathsheba

回答

2

的原因是,你想輸出BufferedWriter作爲一個字符串,而不是它封裝了StringWriter。正確的方式如下所示:

StringWriter sw = new StringWriter(); 
BufferedWriter writer = new BufferedWriter(sw); 
... do your writing into writer ... 
return sw.toString(); 

P.S:而在一般情況它是你的BufferedWriter試圖使用結果之前flush()一個好主意。或者更好,close()吧。你甚至可以關閉你的StringWriter,儘管在這種情況下它沒有什麼區別,關閉你的流和作家是一個很好的習慣。

3

@Payal問題是在你的return語句

writer.toString(); 

它返回作家對象的地址。你應該做的是:

StringWriter strWriter = new StringWriter(); 
writer = new BufferedWriter(strWriter); 

return strWriter.toString(); 
1

writer是一個緩衝的作家。在緩衝作家調用toString將返回的BufferedWriter類實例的字符串表示:

[email protected] 

,如果你對底層StringWriter實例調用toString你會得到你寫信給作家的字符串數據。

3

用你的StringWriter得到迴應,不要忘記刷新。

這是你的方法有一些正確的格式:

static BufferedWriter writer = null; 

public static String getTrimmedResponse(BufferedReader b) 
{ 
    StringWriter sw = new StringWriter(); 
    writer = new BufferedWriter(sw); 
    int count = 0; 

    try { 

     for (String line; (line = b.readLine()) != null;) { 
      if (count++ % maxlines == 0) { 
       line = line.replaceAll("\\n", ""); 
      } 

      String trimmedLine = line.trim(); 
      if (trimmedLine.charAt(trimmedLine.length() - 1) == '>') { 
       writer.append(trimmedLine); 
      } else { 
       writer.write(line); 
       writer.newLine(); 
      } 
     } 

     //writer.flush(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
        Log.i("texception", e+""); 
    } finally { 
     try { 
          // close flushes before closing 
      writer.close(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sw.toString(); 
} 
+1

+1提醒沖洗。 (儘管你並不需要單獨的flush()和close(),但它肯定不會受到傷害)。 – biziclop

+0

True,edited。謝謝 –