Clase Java.io.Reader en Java

Es una clase abstracta para leer flujos de caracteres. Los únicos métodos que debe implementar una subclase son read(char[], int, int) y close(). Sin embargo, la mayoría de las subclases anularán algunos de los métodos definidos aquí para proporcionar una mayor eficiencia, funcionalidad adicional o ambos.
Constructores:

  • protected Reader() : crea un nuevo lector de flujo de caracteres cuyas secciones críticas se sincronizarán en el propio lector.
  • Lector protegido (bloqueo de objeto): crea un nuevo lector de flujo de caracteres cuyas secciones críticas se sincronizarán en el objeto dado.

Métodos:

  • abstract void close() : Cierra la transmisión y libera cualquier recurso del sistema asociado con ella. Una vez que se ha cerrado la secuencia, las invocaciones adicionales de read(), ready(), mark(), reset() o skip() arrojarán una IOException. Cerrar una transmisión previamente cerrada no tiene ningún efecto.
    Syntax :public abstract void close()
                        throws IOException
    Throws:
    IOException 
  • void mark(int readAheadLimit) : marca la posición actual en la secuencia. Las llamadas posteriores a reset() intentarán reposicionar la secuencia en este punto. No todos los flujos de entrada de caracteres admiten la operación mark().
    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. After reading this many characters, 
    attempting to reset the stream may fail.
    Throws:
    IOException 
  • boolean markSupported() : indica si esta transmisión admite la operación mark(). La implementación predeterminada siempre devuelve falso. Las subclases deben anular este método.
    Syntax :public boolean markSupported()
    Returns:
    true if and only if this stream supports the mark operation.
  • int read() : Lee un solo carácter. Este método se bloqueará hasta que haya un carácter disponible, se produzca un error de E/S o se alcance el final de la transmisión.
    Las subclases que pretenden admitir la entrada eficiente de un solo carácter deben anular este método.
    Syntax :public int read()
             throws IOException
    Returns:
    The character read, as an integer in the range 0 to 65535 (0x00-0xffff), 
    or -1 if the end of the stream has been reached
    Throws:
    IOException 
  • int read(char[] cbuf) : lee caracteres en una array. Este método se bloqueará hasta que haya alguna entrada disponible, se produzca un error de E/S o se alcance el final de la transmisión.
    Syntax :public int read(char[] cbuf)
             throws IOException
    Parameters:
    cbuf - Destination buffer
    Returns:
    The number of characters read, or -1 if the end of the stream has been reached
    Throws:
    IOException 
  • abstract int read(char[] cbuf, int off, int len) : lee caracteres en una parte de una array. Este método se bloqueará hasta que alguna entrada esté disponible, se produzca un error de E/S o se alcance el final de la secuencia .
    Syntax :public abstract int read(char[] cbuf,
           int off,
           int len)
                      throws IOException
    Parameters:
    cbuf - Destination buffer
    off - Offset at which to start storing 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 
  • int read(CharBuffer target) : Intenta leer caracteres en el búfer de caracteres especificado. El búfer se usa como depósito de caracteres tal cual: los únicos cambios realizados son los resultados de una operación de colocación. No se realiza ningún volteo o rebobinado del búfer.
    Syntax :public int read(CharBuffer target)
             throws IOException
    Parameters:
    target - the buffer to read characters into
    Returns:
    The number of characters added to the buffer, 
    or -1 if this source of characters is at its end
    Throws:
    IOException 
    NullPointerException
    ReadOnlyBufferException
  • 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, false otherwise. 
    Note that returning false does not guarantee that the next read will block.
    Throws:
    IOException 
  • void reset() : reinicia la transmisión. Si se marcó la secuencia, intente reposicionarla en la marca. Si la transmisión no se ha marcado, intente restablecerla de alguna manera apropiada para la transmisión en particular, por ejemplo, reubicándola en su punto de inicio. No todos los flujos de entrada de caracteres admiten la operación reset(), y algunos admiten reset() sin admitir mark().
    Syntax :public void reset()
               throws IOException
    Throws:
    IOException
  • long skip(long n) : Salta caracteres. Este método se bloqueará hasta que algunos caracteres estén disponibles, se produzca un error de E/S o se alcance el final de la secuencia.
    Syntax :public long skip(long n)
              throws IOException
    Parameters:
    n - The number of characters to skip
    Returns:
    The number of characters actually skipped
    Throws:
    IllegalArgumentException - If n is negative.
    IOException
//Java program demonstrating Reader methods
import java.io.*;
import java.nio.CharBuffer;
import java.util.Arrays;
class ReaderDemo
{
    public static void main(String[] args) throws IOException
    {
        Reader r = new FileReader("file.txt");
        PrintStream out = System.out;
        char c[] = new char[10];
        CharBuffer cf = CharBuffer.wrap(c);
  
        //illustrating markSupported()
        if(r.markSupported()) {
            //illustrating mark()
            r.mark(100);
            out.println("mark method is supported");
        }
        //skipping 5 characters
        r.skip(5);
  
        //checking whether this stream is ready to be read.
        if(r.ready()) 
        {
            //illustrating read(char[] cbuf,int off,int len)
            r.read(c,0,10);
            out.println(Arrays.toString(c));
  
            //illustrating read(CharBuffer target )
            r.read(cf);
            out.println(Arrays.toString(cf.array()));
              
            //illustrating read()
            out.println((char)r.read());
        }
        //closing the stream
        r.close();
    }
}

Producción :

[f, g, h, i, g, k, l, m, n, o]
[p, q, r, s, t, u, v, w, x, y]
z

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 *