2012-10-26 82 views
2

我得到一個非常長的字符串作爲Web服務的響應我收集它在使用StringBuilder,但我無法獲得完整的價值我也用StringBuffer但已沒有成功。很長的字符串作爲Web服務的響應

這裏是我使用的代碼:

private static String read(InputStream in) throws IOException { 
    //StringBuilder sb = new StringBuilder(1000); 
    StringBuffer sb = new StringBuffer(); 
    String s = ""; 
    BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); 
    for (String line = r.readLine(); line != null; line = r.readLine()) { 
     sb.append(line); 
     s += line; 
    } in .close(); 

    System.out.println("Response from Input Stream Reader >>>" + sb.toString()); 
    System.out.println("Response from Input S >>>>>>>>>>>>" + s); 
    return sb.toString(); 
} 

任何幫助表示讚賞。

回答

3

您還可以在字符串數組分割字符串才能看到所有的人都

String delimiter = "put a delimiter here e.g.: \n"; 
String[] datas=sb.toString().split(delimiter); 

for(String string datas){ 
System.out.println("Response from Input S >>>>>>>>>>>>" + string); 
} 
3

String可能無法完全打印到控制檯,但它實際上在那裏。將其保存到文件中以便查看它。

+0

upvote爲正確的答案,但它的標記答案,幫助我感謝了很多快速反應 –

1

我不認爲你輸入過大的字符串,但不僅沒有顯示控制檯,因爲它不接受太長的線。不管怎麼說,這裏是一個非常巨大的輸入作爲字符解決方案:

private static String[] readHugeStream(InputStream in) throws IOException { 
    LinkedList<String> dataList = new LinkedList<>(); 
    boolean finished = false; 
    // 
    BufferedReader r = new BufferedReader(new InputStreamReader(in), 0xFFFFFF); 
    String line = r.readLine(); 
    while (!finished) { 
     int lengthRead = 0; 
     StringBuilder sb = new StringBuilder(); 
     while (!finished) { 
      line = r.readLine(); 
      if (line == null) { 
       finished = true; 
      } else { 
       lengthRead += line.length(); 
       if (lengthRead == Integer.MAX_VALUE) { 
        break; 
       } 
       sb.append(line); 
      } 
     } 
     if (sb.length() != 0) { 
      dataList.add(sb.toString()); 
     } 
    } 
    in.close(); 
    String[] data = dataList.toArray(new String[]{}); 
    /// 
    return data; 
} 

public static void main(String[] args) { 
    try { 
     String[] data = readHugeStream(new FileInputStream("<big file>")); 
    } catch (IOException ex) { 
     Logger.getLogger(StackoverflowStringLong.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (OutOfMemoryError ex) { 
     System.out.println("out of memory..."); 
    } 
} 
0

的System.out.println()不打印所有字符,它只能顯示有限的控制檯的字符數。您可以在SD卡中創建一個文件並將其作爲文本文檔複製到您的文本中以檢查您的確切響應。

try 
       { 
         File root = new File(Environment.getExternalStorageDirectory(), "Responsefromserver"); 
         if (!root.exists()) 
         { 
          root.mkdirs(); 
         } 
         File gpxfile = new File(root, "response.txt"); 
         FileWriter writer = new FileWriter(gpxfile); 
         writer.append(totalResponse); 
         writer.flush(); 
         writer.close(); 
        } 
        catch(IOException e) 
        { 
          System.out.println("Error:::::::::::::"+e.getMessage()); 
         throw e; 

        }