2013-07-19 39 views
12

我想我StringReader转换回常规String,如图所示:如何将StringReader转换为String?

String string = reader.toString(); 

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

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

我得到的是一个指针值,像这样:

[email protected] 

我在读取字符串回来时做错了什么?

+5

显然,你是。 http://docs.oracle.com/javase/7/docs/api/java/io/StringReader.html –

+1

如果不使用读取,您无法从字符串读取器获取字符串(。 – hexafraction

回答

9

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

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

我推荐使用read的重载,它接受一个字符数组。批量读取比单字符读取更快。

即。

//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); 
0

您正在打印出实际StringReader对象的toString(),而不是StringReader正在读取的String的内容。

您需要使用read()和/或read(char[] cbuf, int off, int len)方法来读取字符串中的实际字符。

1

reader.toString();会给你从Object类调​​用通用toString()方法的结果。如果你使用的方法toString()StringReader对象,你将打印对象的内存位置

int i;    
do { 
    i = reader.read(); 
    char c = (char) i; 
    // do whatever you want with the char here... 

} while (i != -1); 
+0

使用数组进行批量读取比一次读一个字符要快。 –

0

可以使用read()方法。你有哟使用这种方法之一:

read() 读取单个字符。

read(char[] cbuf, int off, int len) 将字符读入数组的一部分。

这里的示例:

 String s = "Hello World"; 

    // create a new StringReader 
    StringReader sr = new StringReader(s); 

    try { 
     // read the first five chars 
     for (int i = 0; i < s.length(); i++) { 
      char c = (char) sr.read(); 
      System.out.print("" + c); 
     } 

     // close the stream 
     sr.close(); 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
1

调用toString()方法将给出StringReader类的对象。如果哟想它的内容,那么你需要调用read方法上StringReader这样的:

public class StringReaderExample { 

    public static void main(String[] args) { 

     String s = "Hello World"; 

     // create a new StringReader 
     StringReader sr = new StringReader(s); 

     try { 
     // read the first five chars 
     for (int i = 0; i < 5; i++) { 
      char c = (char) sr.read(); 
      System.out.print("" + c); 
     } 

     // close the stream 
     sr.close(); 

     } catch (IOException ex) { 
     ex.printStackTrace(); 
     } 
    } 
} 

对于教程,你可以使用这个link

20
import org.apache.commons.io.IOUtils; 

String string = IOUtils.toString(reader); 
4

或者使用CharStreams从谷歌番石榴库:

CharStreams.toString(stringReader); 
3

如果你不想使用外部库:

Scanner scanner = new Scanner(reader).useDelimiter("\\A"); 
String str = scanner.hasNext() ? scanner.next() : ""; 

的原因hasNext()检查是next()爆炸了如果阅读器包装空白(零长度)字符串,则为NoSuchElementException

相关问题