当我从此页面检索歌词时:here,新行消失。我在单个String中检索xml,为了这个问题的简单性,我使用substring来减去歌词。当我使用以下代码打印每个字符时,没有可见的换行符。
if (response.contains("lyrics_body")) {
lyrics = response.substring(response.indexOf("<lyrics_body>") + 13, response.indexOf("</lyrics_body>"));
StringReader sr = new StringReader(lyrics);
int l;
try {
while ((l = sr.read()) != -1) {
System.out.println(":" + l);
}
} catch (Exception ex) {
}
}
部分输出:
85 U
104 h
110 n
32
116 t
105 i
115 s
115 s
32
117 u
104 h
110 n
32
116 t
105 i
115 s
115 s
32
117 u
104 h
110 n
32
116 t
105 i
115 s
115 s
32
98 b
97 a
98 b
121 y
68 d
111 o
103 g
32
119 w
105 i
108 l
108 l
.
.
为了清晰起见,我在数字后面添加了个别字符,显然在'baby'和'dog'之间应该有换行符。
我该如何解析这个换行符?
答案 0 :(得分:1)
我从某个地方使用过这个来源:
public static String postData(String base, List<BasicNameValuePair> data) throws IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(base);
HttpResponse response = null;
String line = "";
StringBuilder total = new StringBuilder();
HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);
try {
httppost.setEntity(new UrlEncodedFormEntity(data));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
total.append("\n"); //I'VE JUST ADDED THIS LINE
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return full string
return total.toString();
}
显然,它所说的“我刚添加了这一行”的部分就是问题,感谢Jon让我看看这段代码!
答案 1 :(得分:0)
将StringReader
包裹在BufferedReader
中并使用readLine()
BufferedReader bufferedReader = new BufferedReader(new StringReader(lyrics));
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
// do something with line
}