这个方法没有返回有效的字符串。可能是什么原因??
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();
}
答案 0 :(得分:3)
@Payal问题在您的退货声明中
writer.toString();
它返回writer对象的地址。你应该做的是:
StringWriter strWriter = new StringWriter();
writer = new BufferedWriter(strWriter);
和
return strWriter.toString();
答案 1 :(得分: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();
}
答案 2 :(得分:2)
原因是您尝试将BufferedWriter
输出为字符串而不是它包装的StringWriter
。正确的习语看起来像这样:
StringWriter sw = new StringWriter();
BufferedWriter writer = new BufferedWriter( sw );
... do your writing into writer ...
return sw.toString();
P.S。:一般来说,在尝试使用结果之前,flush()
BufferedWriter
是个好主意。或者甚至更好,close()
它。你甚至可以关闭你的StringWriter
,即使在这种情况下没有任何区别,关闭你的流和作家是一个很好的习惯。
答案 3 :(得分:1)
writer
是一个缓冲的作家。在缓冲的writer上调用toString
将返回BufferedWriter类实例的字符串表示形式:
java.io.BufferedWriter@1e311410
如果您在底层toString
实例上调用StringWriter
,您将获得写入编写器的字符串数据。