简体   繁体   English

如何使用Java中的StringReader类读取字符串?

[英]How can I read a String using StringReader class in Java?

I have to read a String char by char using the String Reader Class. 我必须使用String Reader Class逐字符读取String char。 I have written this code: 我写了这段代码:

String string = "Hello, World!";
StringReader stringReader = new StringReader(string);

while(stringReader.ready())
{
   System.out.println(stringReader.read());
}

But the loop doesn't end with the end of the string, it is infinite! 但是循环不会以字符串的结尾结束,它是无限的! Why? 为什么?

I tried also to do that: 我也尝试这样做:

while(stringReader.read()!=-1)
{
   System.out.println(stringReader.read());
}

The loop isn't infinite...but it jumps some chars...how can I read all the String? 循环不是无限的...但是它跳了一些字符...我如何读取所有String?

Try this: 尝试这个:

    String str = "Hello, World!";

    //Create StringReader instance
    StringReader reader = new StringReader(str);
    int c = reader.read();
    while (c != -1){
        //Converting to character
        System.out.print((char)c);
        c = reader.read();
    }
    //Closing the file io
    reader.close();

The ready method tells you whether the next call to read won't block. ready方法告诉您下一个read调用是否不会阻塞。

Returns: True if the next read() is guaranteed not to block for input, false otherwise. 返回:如果保证下一个read()不会阻塞输入,则返回true,否则返回false。

Once you get to the end of the string, it certainly won't block; 一旦到达字符串的末尾,它肯定不会阻塞。 you've reached the end of the string. 您已经到达字符串的末尾。 With a String , the contents are already present; 使用String ,内容已经存在; a StringReader should always return true for ready . StringReader应该始终返回trueready

You are skipping characters when you call read twice per loop -- once in the while condition and once in the body. 在每个循环调用两次read时,您正在跳过字符-一次在while条件下,一次在主体中。 Assign it to a variable instead. 而是将其分配给变量。

int c;
while((c = stringReader.read()) !=  -1)
{
    System.out.println((char) c);
}

You can also do what you'd normally do any other kind of Reader -- wrap it in a BufferedReader so you can call nextLine or wrap it in a Scanner . 您还可以像平常其他类型的Reader -将其包装在BufferedReader以便可以调用nextLine或将其包装在Scanner

BufferedReader bf = new BufferedReader(stringReader);

or 要么

Scanner strScanner = new Scanner(stringReader);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM