【问题标题】:How can I read a String using StringReader class in Java?如何在 Java 中使用 StringReader 类读取字符串?
【发布时间】:2016-02-04 21:19:45
【问题描述】:

我必须使用字符串阅读器类逐个字符地读取字符串。我写了这段代码:

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

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

但是循环并没有以字符串的结尾结束,它是无限的!为什么?

我也尝试过这样做:

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

循环不是无限的……但它会跳过一些字符……我怎样才能读取所有的字符串?

【问题讨论】:

    标签: java stream stringreader


    【解决方案1】:

    试试这个:

        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();
    

    【讨论】:

      【解决方案2】:

      ready method 告诉您下次调用 read 是否不会阻塞。

      返回: 如果保证下一个 read() 不会阻塞输入,则为 true,否则为 false。

      一旦你到达字符串的末尾,它肯定不会阻塞;你已经到了字符串的末尾。使用String,内容已经存在; StringReader 应始终为 ready 返回 true

      当您在每个循环中调用两次 read 时,您正在跳过字符——一次在 while 条件中,一次在正文中。而是将其分配给一个变量。

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

      你也可以做你通常会做的任何其他类型的Reader - 将其包装在BufferedReader中,这样你就可以调用nextLine或将其包装在Scanner中。

      BufferedReader bf = new BufferedReader(stringReader);
      

      Scanner strScanner = new Scanner(stringReader);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-27
        • 2021-05-13
        • 2011-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        相关资源
        最近更新 更多