Método StringReader read(char[], int, int) en Java con ejemplos

El método read(char[], int, int) de la clase StringReader en Java se usa para leer los caracteres de longitud especificados en una array en un desplazamiento especificado. Este método bloquea la transmisión hasta que:

  • Ha tomado algo de entrada de la corriente.
  • Se ha producido alguna IOException
  • Ha llegado al final de la secuencia durante la lectura.

Sintaxis:

public int read(char[] charArray, int offset, int longitud)

Parámetros: Este método acepta tres parámetros obligatorios:

  • charArray que es la array de caracteres que se escribirá en el Stream.
  • offset , que es el índice de desplazamiento en el que se escribirán los caracteres en la array.
  • longitud que es el número de caracteres que se escribirán en la array.

Valor devuelto: este método devuelve un valor entero que es el número de caracteres leídos de la secuencia. Devuelve -1 si no se ha leído ningún carácter.

Excepción: este método arroja las siguientes excepciones:

  • IOException: si se produce algún error durante la salida de entrada.
  • IndexOutOfBoundsException: si el valor de desplazamiento no está dentro del rango de la array de caracteres

Los siguientes métodos ilustran el funcionamiento del método read(char[], int, int):

Programa 1:

// Java program to demonstrate
// StringReader read(char[], int, int) method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
            String str = "GeeksForGeeks";
  
            // Create a StringReader instance
            StringReader reader
                = new StringReader(str);
  
            // Get the character array
            // to be read from the stream
            char[] charArray = new char[5];
  
            // Get the offset index
            int offset = 0;
  
            // Get the length
            int length = 5;
  
            // Read the charArray
            // to this reader using read() method
            // This will put the str in the stream
            // till it is read by the reader
            reader.read(charArray, offset, length);
  
            // Print the read charArray
            System.out.println(
                Arrays.toString(charArray));
  
            reader.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
Producción:

[G, e, e, k, s]

Programa 2:

// Java program to demonstrate
// StringReader read(char[], int, int) method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
            String str = "GeeksForGeeks";
  
            // Create a StringReader instance
            StringReader reader
                = new StringReader(str);
  
            // Get the character array
            // to be read from the stream
            char[] charArray
                = new char[13];
  
            // Get the offset index
            int offset = 0;
  
            // Get the length
            int length = 13;
  
            // Read the charArray
            // to this reader using read() method
            // This will put the str in the stream
            // till it is read by the reader
            reader.read(charArray, offset, length);
  
            // Print the read charArray
            System.out.println(
                Arrays.toString(charArray));
  
            reader.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
Producción:

[G, e, e, k, s, F, o, r, G, e, e, k, s]

Referencia: https://docs.oracle.com/javase/9/docs/api/java/io/StringReader.html#read-char:A-int-int-

Publicación traducida automáticamente

Artículo escrito por Code_r 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 *