Java中的 PushbackReader read(char, int, int) 方法和示例
Java中PushbackReader类的read(char[], int, int)方法用于将指定长度的字符读入指定偏移量的数组中。此方法阻塞流直到:
- 它从流中获取了一些输入。
- 发生了一些 IOException
- 它在读取时已到达流的末尾。
句法:
public int read(char[] charArray,
int offset,
int length)
参数:此方法接受三个强制参数:
- charArray是要写入 Stream 的字符数组。
- 偏移量,它是要在数组中写入字符的偏移量索引。
- length是要写入数组的字符数。
返回值:此方法返回一个整数值,它是从流中读取的字符数。如果没有读取任何字符,则返回 -1。
异常:此方法抛出以下异常:
- IOException:如果输入输出时发生错误。
- IndexOutOfBoundsException:如果偏移值不在字符数组范围内
下面的方法说明了 read(char[], int, int) 方法的工作:
方案一:
// Java program to demonstrate
// PushbackReader read(char, int, int) method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
try {
// Initializing a StringReader
// and PushbackReader
String s = "GeeksForGeeks";
StringReader stringReader
= new StringReader(s);
PushbackReader pushbackReader
= new PushbackReader(stringReader);
// 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
pushbackReader
.read(charArray, offset, length);
// Print the read charArray
System.out.println(
Arrays.toString(charArray));
// Close the stream
pushbackReader.close();
System.out.println("Stream Closed.");
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
[G, e, e, k, s]
Stream Closed.
方案二:
// Java program to demonstrate
// PushbackReader read(char, int, int) method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
try {
// Initializing a StringReader
// and PushbackReader
String s = "GFG";
StringReader stringReader
= new StringReader(s);
PushbackReader pushbackReader
= new PushbackReader(stringReader);
// 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 = 2;
// Read the charArray
// to this reader using read() method
// This will put the str in the stream
// till it is read by the reader
pushbackReader
.read(charArray, offset, length);
// Print the read charArray
System.out.println(
Arrays.toString(charArray));
// Close the stream
pushbackReader.close();
System.out.println("Stream Closed.");
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
[G, F,,, ]
Stream Closed.
参考: https://docs.oracle.com/javase/9/docs/api/ Java/io/PushbackReader.html#read-char:A-int-int-