Clase Java.io.StringReader en Java

Esta es una clase de flujo de caracteres cuya fuente es una string.
Constructor:

  • StringReader(String s) : Crea un nuevo lector de strings.
  • Métodos :

    • void close() : Cierra la transmisión y libera cualquier recurso del sistema asociado con ella. Una vez que se ha cerrado la transmisión, las invocaciones adicionales de read(), ready(), mark() o reset() arrojarán una IOException. Cerrar una transmisión previamente cerrada no tiene ningún efecto.
      Syntax :public void close()
      
    • void mark(int readAheadLimit) : Marca la posición actual en la secuencia. Las llamadas subsiguientes a reset() reposicionarán la transmisión a este punto.
      Syntax :public void mark(int readAheadLimit)
                throws IOException
      Parameters:
      readAheadLimit - Limit on the number of characters that may 
      be read while still preserving the mark. Because the stream's input 
      comes from a string, there is no actual limit, so this argument 
      must not be negative, but is otherwise ignored.
      Throws:
      IllegalArgumentException
      IOException
    • boolean markSupported() : indica si esta secuencia admite la operación mark(), lo cual es cierto.
      Syntax :public boolean markSupported()
      Returns:
      true if and only if this stream supports the mark operation.
    • int read() : Lee un solo carácter.
      Syntax :public int read()
               throws IOException
      Returns:
      The character read, or -1 if the end of the stream has been reached
      Throws:
      IOException
    • int read(char[] cbuf, int off, int len) : Lee caracteres en una parte de una array.
      Syntax :public int read(char[] cbuf,
             int off,
             int len)
               throws IOException
      Parameters:
      cbuf - Destination buffer
      off - Offset at which to start writing characters
      len - Maximum number of characters to read
      Returns:
      The number of characters read, or -1 if the end of the stream has been reached
      Throws:
      IOException
    • boolean ready() : indica si este flujo está listo para ser leído.
      Syntax :public boolean ready()
                    throws IOException
      Returns:
      True if the next read() is guaranteed not to block for input
      Throws:
      IOException
    • void reset() : restablece la secuencia a la marca más reciente o al comienzo de la string si nunca se ha marcado.
      Syntax :public void reset()
                 throws IOException
      Throws:
      IOException 
    • long skip(long ns) : Omite el número especificado de caracteres en la transmisión. Devuelve el número de caracteres que se omitieron.
      El parámetro ns puede ser negativo, aunque el método skip de la superclase Reader arroja una excepción en este caso. Los valores negativos de ns hacen que la transmisión salte hacia atrás. Los valores de retorno negativos indican un salto hacia atrás. No es posible saltar hacia atrás más allá del comienzo de la string.

      Si se ha leído u omitido toda la string, este método no tiene ningún efecto y siempre devuelve 0.

      Syntax :public long skip(long ns)
                throws IOException
      Parameters:
      ns - The number of characters to skip
      Returns:
      The number of characters actually skipped
      Throws:
      IOException

    Programa :

    //Java program demonstrating StringReader methods
    import java.io.IOException;
    import java.io.StringReader;
    class StringReaderDemo
    {
        public static void main(String[] args) throws IOException
        {
            StringReader str = new StringReader("GeeksforGeeks");
            char c[]=new char[7];
      
            //illustrating markSupported()
            if(str.markSupported())
            {
                System.out.println("Mark method is supported");
                // illustrating mark()
                str.mark(100);
            }
              
            //illustrating skip() method
            str.skip(5);
              
            //whether this stream is ready to be read.
            if(str.ready())
            {
                //illustrating read() method
                System.out.print((char)str.read());
                  
                //illustrating read(char cff[],int off,int len)
                str.read(c);
                for (int i = 0; i <7 ; i++) 
                {
                    System.out.print(c[i]);
                }
            }
              
            //illustrating reset() method
            str.reset();
              
            for (int i = 0; i < 5; i++) 
            {
                System.out.print((char)str.read());
            }
              
            //illustrating close()
            str.close();
        }
    }
    

    Producción :

    Mark method is supported
    forGeeksGeeks

    Este artículo es una contribución de Nishant Sharma . Si le gusta GeeksforGeeks y le gustaría contribuir, también puede escribir un artículo usando contribuya.geeksforgeeks.org o envíe su artículo por correo a contribuya@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.

    Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.

    Publicación traducida automáticamente

    Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

    Deja una respuesta

    Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *