Java Reader read(char[], int, int)方法及示例
Java中Reader类的read(char[], int, int)方法用于在指定的偏移量处将指定长度的字符读入一个数组。这个方法阻塞了流,直到。
它已经从流中获取了一些输入。发生了一些IOException读取时已经达到了流的末端。语法。
public int read(char[] charArray, int offset, int length)
参数。这个方法接受三个强制性参数。
charArray是要写入流中的字符数组。offset,是要写入数组中的字符的偏移索引。length是要写入数组中的字符数。返回值。该方法返回一个整数,即从流中读取的字符数。如果没有读取任何字符,则返回-1。
异常情况。该方法会抛出以下异常。
IOException:如果在输入输出时发生一些错误。IndexOutOfBoundsException:如果偏移值不在字符阵列的范围内。下面的方法说明了read(char[], int, int)方法的工作。
程序1:
// Java program to demonstrate// Reader 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 Reader instance Reader 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); } }}
输出:
[G, e, e, k, s]
程序2。
// Java program to demonstrate// Reader 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 Reader instance Reader reader = new StringReader(str); // Get the character array // to be read from the stream char[] charArray = new char[str.length()]; // Get the offset index int offset = 0; // Get the length int length = str.length(); // 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); } }}输出:
[G, e, e, k, s, F, o, r, G, e, e, k, s]
参考资料: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read-char:A-int-int-
