如何将StringReader转换为String? [英] How do I convert a StringReader to a String?

查看:564
本文介绍了如何将StringReader转换为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 StringReader 转换回常规字符串,如下所示:

I'm trying to convert my StringReader back to a regular String, as shown:

String string = reader.toString();

但是当我尝试读出这个字符串时,就像这样:

But when I try to read this string out, like this:

System.out.println("string: "+string);

我得到的只是一个指针值,如下所示:

All I get is a pointer value, like this:

java.io.StringReader@2c552c55

我在读回字符串时做错了吗?

Am I doing something wrong in reading the string back?

推荐答案

StringReader toString 方法不返回 StringReader 内部缓冲区。

The StringReader's toString method does not return the StringReader internal buffers.

你需要阅读 StringReader 才能得到这个。

You'll need to read from the StringReader to get this.

我建议使用接受字符数组的read重载。批量读取比单个字符读取更快。

I recommend using the overload of read which accepts a character array. Bulk reads are faster than single character reads.

ie。

//use string builder to avoid unnecessary string creation.
StringBuilder builder = new StringBuilder();
int charsRead = -1;
char[] chars = new char[100];
do{
    charsRead = reader.read(chars,0,chars.length);
    //if we have valid chars, append them to end of string.
    if(charsRead>0)
        builder.append(chars,0,charsRead);
}while(charsRead>0);
String stringReadFromReader = builder.toString();
System.out.println("String read = "+stringReadFromReader);

这篇关于如何将StringReader转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆