Java中的StringReader類的mark()方法用於在調用reset()後將流標記為從開始讀取流的檢查點。 StringReader類的所有子類均不支持此方法。
用法:
public void mark(int readAheadLimit)
參數:此方法接受強製性參數readAheadLimit,該參數是在保留標記的同時可以讀取的字符數限製。讀取了這麽多字符後,嘗試重置流可能會失敗。
返回值:此方法不返回任何值。
異常:如果在不支持輸入輸出或mark()方法時發生某些錯誤,則此方法將引發IOException。
下麵的方法說明了mark()方法的用法方式:
示例1:
// Java program to demonstrate
// StringReader mark() method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
try {
String str = "GeeksForGeeks";
// Create a StringReader instance
StringReader reader
= new StringReader(str);
// Get the character
// to be read from the stream
int ch;
// Read the first 10 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 < 10; i++) {
ch = reader.read();
System.out.print((char)ch);
}
System.out.println();
// mark the stream for
// 5 characters using mark()
reader.mark(5);
// reset the stream position
reader.reset();
// Read the 5 characters from marked position
// 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);
}
}
}
輸出:
GeeksForGe eks??
示例2:
// Java program to demonstrate
// StringReader mark() method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
try {
String str = "GeeksForGeeks";
// Create a StringReader instance
StringReader reader
= new StringReader(str);
// Get the character
// to be read from the stream
int ch;
// Read the first 10 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 < 10; i++) {
ch = reader.read();
System.out.print((char)ch);
}
System.out.println();
// mark the stream for
// 10 characters using mark()
reader.mark(10);
// reset the stream position
reader.reset();
// Read the 1 characters from marked position
// to this reader using read() method
for (int i = 0; i < 1; i++) {
ch = reader.read();
System.out.print((char)ch);
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
GeeksForGe e
參考: https://docs.oracle.com/javase/9/docs/api/java/io/StringReader.html#mark-int-
相關用法
- Java StringReader markSupported()用法及代碼示例
- Java StringReader close()用法及代碼示例
- Java StringReader reset()用法及代碼示例
- Java StringReader read()用法及代碼示例
- Java StringReader ready()用法及代碼示例
- Java StringReader read(char[], int, int)用法及代碼示例
- Java StringReader read(char[])用法及代碼示例
- Java StringReader read(CharBuffer)用法及代碼示例
- Java StringReader skip(long)用法及代碼示例
- Java Java.io.StringReader用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 StringReader mark(int) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。