Java Reader read(CharBuffer)方法及示例

来源:这里教程网 时间:2026-02-17 21:07:45 作者:

Java Reader read(CharBuffer)方法及示例

Java中Reader类的read(CharBuffer)方法是用来读取指定的字符到CharBuffer实例中。这个方法阻塞了流,直到。

它已经从流中获取了一些输入。发生了一些IOException读取时已经到达了流的末端。

语法。

public int read(CharBuffer charBuffer)

参数。该方法接受一个强制性参数charBuffer,它是要写入Stream的CharBuffer实例。

返回值。该方法返回一个整数,即从流中读取的字符数。如果没有读取任何字符,则返回-1。

异常。该方法会抛出以下异常。

IOException:如果在输入输出时发生一些错误。NullPointerException:如果要填充的CharBuffer实例为空。ReadOnlyBufferException:如果要填充的CharBuffer实例是一个只读缓冲区。

下面的方法说明了read(CharBuffer)方法的工作。

程序 1:

// Java program to demonstrate// Reader read(CharBuffer) method  import java.io.*;import java.util.*;import java.nio.CharBuffer;  class GFG {    public static void main(String[] args)    {          try {              String str = "GeeksForGeeks";              // Create a Reader instance            Reader reader                = new StringReader(str);              // Get the CharBuffer instance            // to be read from the stream            CharBuffer charBuffer                = CharBuffer.allocate(5);              // Read the charBuffer            // to this reader using read() method            // This will put the str in the stream            // till it is read by the reader            reader.read(charBuffer);              // Print the read charBuffer            System.out.println(charBuffer                                   .flip()                                   .toString());              reader.close();        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

Geeks

程序2。

// Java program to demonstrate// Reader read(CharBuffer) method  import java.io.*;import java.util.*;import java.nio.CharBuffer;  class GFG {    public static void main(String[] args)    {          try {              String str = "GeeksForGeeks";              // Create a Reader instance            Reader reader                = new StringReader(str);              // Get the CharBuffer instance            // to be read from the stream            CharBuffer charBuffer                = CharBuffer                      .allocate(                          str.length());              // Read the charBuffer            // to this reader using read() method            // This will put the str in the stream            // till it is read by the reader            reader.read(charBuffer);              // Print the read charBuffer            System.out.println(charBuffer                                   .flip()                                   .toString());              reader.close();        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

GeeksForGeeks

参考资料: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read-java.nio.CharBuffer-

相关推荐