Java Reader skip(long)方法及示例
Java中Reader类的skip(long)方法是用来跳过流中指定的字符数的。这个数量的字符被指定为参数。如果它跳过的字符数达到了流的末端,它将阻塞流,直到获得一些字符,或者抛出IOException。
语法。
public long skip(long numberOfChar)
参数。该方法接受一个参数numberOfChar,它是该方法要跳过的字符数。
返回值。此方法返回一个长值,即此方法跳过的实际字符数。
异常情况。这个方法会抛出。
- IOException:如果在输入输出时发生一些错误
- IllegalArgumentException:如果传递的numberOfChar是负数。
下面的方法说明了skip(long)方法的工作。
程序 1:
// Java program to demonstrate
// Reader skip(long) 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
// to be read from the stream
int ch;
// Read the first 5 characters
// to this reader using read() method
// This will put the str in the stream
// till it is read by the reader
for (int i = 0; i < 5; i++) {
ch = reader.read();
System.out.print((char)ch);
}
System.out.println();
// skip 3 characters using skip(long)
reader.skip(3);
System.out.println("Next 3 characters skipped.");
// Read the 5 characters
// to this reader using read() method
for (int i = 0; i < 5; i++) {
ch = reader.read();
System.out.print((char)ch);
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Geeks
Next 3 characters skipped.
Geeks
程序2。
// Java program to demonstrate
// Reader skip(long) 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
// to be read from the stream
int ch;
// Read the first 5 characters
// to this reader using read() method
// This will put the str in the stream
// till it is read by the reader
for (int i = 0; i < 5; i++) {
ch = reader.read();
System.out.print((char)ch);
}
System.out.println();
// skip 10 characters using skip(long)
reader.skip(10);
// Read the 5 characters
// to this reader using read() method
for (int i = 0; i < 5; i++) {
ch = reader.read();
System.out.print((char)ch);
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Geeks
?????
参考资料: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#skip-long-