Java中Reader類的read(CharBuffer)方法用於將指定的字符讀取到CharBuffer實例中。此方法將流阻塞到:
- 它已從流中獲取了一些輸入。
- 發生了一些IOException
- 閱讀時已到達流的末尾。
用法:
public int read(CharBuffer charBuffer)
參數:此方法接受強製參數charBuffer,該參數是要在Stream中寫入的CharBuffer實例。
返回值:此方法返回一個整數值,該整數值是從流中讀取的字符數。如果未讀取任何字符,則返回-1。
異常:此方法引發以下異常:
- IOException:輸入輸出時發生錯誤。
- NullPointerException :如果要填充的CharBuffer實例為null
- 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-
相關用法
- Java Reader reset()用法及代碼示例
- Java Reader markSupported()用法及代碼示例
- Java Reader ready()用法及代碼示例
- Java Reader mark(int)用法及代碼示例
- Java Reader read()用法及代碼示例
- Java Reader close()用法及代碼示例
- Java Reader skip(long)用法及代碼示例
- Java Reader read(char[], int, int)用法及代碼示例
- Java Reader read(char[])用法及代碼示例
- Java Java.io.Reader用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Reader read(CharBuffer) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。