如何将StringReader转换为String?

编程入门 行业动态 更新时间:2024-10-13 20:20:37
本文介绍了如何将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?

本文发布于:2023-06-08 21:31:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589422.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   StringReader   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!