PushbackInputStream适用于语法解析过程中的语法回退,因为这个类提供了一个有限的字节(内部定义了一个默认长度为1的byte[] buf字节数组)缓冲回退能力,具体流程如下: ①、调用unread()函数时,将任何字节压入byte[](可以是从装饰输入流中读取的字节,也可以是自己定义的字节) buf字节数组头部; ②、在后续调用read()函数时,优先阅读此byte[] buf字节数组中压入的字节; 使用PushbackInputstream进行语法分析时,应注意 unread()函数的调用顺序,EOF 处理及嵌套退货风险等。 因为语法分析器通常需要先预读一个字符来判断类型,如果它不是目标类型,然后返回, InputStream.class PushbackInputStreamam本身并不支持回归.为此设计了class。 许多语法分析需要预读多个字符才能确定 token 类型,如识别 == 和 =、或 /* 注明起始符。Pushbackinputstream默认构造函数 1 字节缓冲(内部定义了默认长度为1的byte[] buf字节数组)根本不够,需要使用
new PushbackInputStream(in, 4)
构建一个长度为4的byte[] 如果支持buf字节数组作为缓冲区,用于覆盖大多数双字符操作符和简单分隔符场景 Unicode 转义(如 或长标识符前缀判断,缓冲区需要更大,但不要盲目设置 同时缓冲区byte[]1024 buf字节数组的长度在结构后不变,在运行过程中无法扩展。例如,以下是识别数字字面量(包括小数点)时的安全退货示例。伪代码如下:
...省略一些代码...
int ch = in.read();
if (ch == '.') {
int next = in.read();
if (Character.isDigit(next)) {
// 确认为小数,继续分析
parseFractionPart();
} else {
// 退回两个字符的不是小数字:‘.' 和 next
in.unread(next);
in.unread('.');
}
} else {
// 其他情况按原逻辑处理
}
...省略一些代码...
1.1、PushbackInputStream源码分析
PushbackInputStream.class UML关系图如下:

PushbackInputStream.class的源代码如下:
package java.io;
public class PushbackInputStream extends FilterInputStream {
字节数组缓冲区有限长度,默认长度为1
protected byte[] buf;
///可读指针,byte[] buf指针(包括指针)索引后的所有字节(有限长度的字节数组缓冲区)都可以读取
protected int pos;
///检查装修输入流是否关闭
private void ensureOpen() throws IOException {
if (in == null)
throw new IOException("Stream closed");
}
//构造函数,in是装饰的输入流,size是byte[] buf(用于返回的字节数组缓冲区长度有限)
public PushbackInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("size <= 0");
}
this.buf = new byte[size];
this.pos = size;///将可读指针指向byte[] buf最后一个索引(字节数组缓冲区有限长度)(size-1)之后
}
//构造函数,in是装饰的输入流
public PushbackInputStream(InputStream in) {
this(in, 1);///构建默认长度为1的byte[] buf(字节数组缓冲区用于回退)
}
/如果byte[] buf(字节数组缓冲区用于回退)中有可读的字节的话,就从该缓冲区中读取1个字节
/如果byte[] buf(字节数组缓冲区用于回退)中没有可读的字节的话,读取从装饰输入流中读取的一个字节
/如果byte[] buf(用于回退的字节数组缓冲区)和装饰输入流中没有可读字节,返回-1
public int read() throws IOException {
ensureOpen();
if (pos < buf.length) {
return buf[pos++] & 0xff;
}
return super.read();
}
//尽可能多地从byte[] buf(用于回退字节数组缓冲区)和装饰输入流中读取len字节至byte[] b的[off,off+len)索引位置分为以下五种场景:
//①、如果byte[] buf(用于回退的字节数组缓冲区)如果有len字节,从缓冲区读取len字节到字节数组byte[] b的[off,off+len)索引位置
//②、如果byte[] buf(用于回退字节数组缓冲区)如果没有字节,且装饰输入流中有len字节,则从装饰输入流中读取len字节至字节数组byte[] b的[off,off+len)索引位置
//③、如果byte[] buf(用于回退的字节数组缓冲区)没有字节,装饰的输入流只有avail(avail<len)从被装饰的输入流中读取avail字节到字节数组byte[] b的[off,off+avail)索引位置
//④、如果byte[] bufavail(用于回退的字节数组缓冲区)(avail<len)如果是字节,就读avail字节,剩下的len-avail字节从装饰输入流中读取,如果装饰输入流中没有len-avail字节,则从装饰输入流中读取多少字节,直到读取装饰输入流,然后将上述两个字节(装饰输入流+字节数组缓冲区)读取(如有x)放入字节数组byte[] b的[off,off+x)索引位置
//⑤、如果byte[] buf(用于返回的字节数组缓冲区)和装饰输入流中没有字节的,返回-1
public int read(byte[] b, int off, int len) throws IOException {
///检查装修输入流是否关闭
ensureOpen();
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {//相当于off + len > b.length(我没有看到源码中这样写代码的好处)
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;//从Pushbackinputstreama len字节在对象中读取==0时,返回0
}
int avail = buf.length - pos;buf实际上装载在用于回退的字节数组缓冲区.length - pos字节
if (avail > 0) {
if (len < avail) {
avail = len;
}
System.arraycopy(buf, pos, b, off, avail);
pos += avail;
off += avail;
len -= avail;
}
if (len > 0) {
len = super.read(b, off, len);
if (len == -1) {
return avail == 0 ? -1 : avail;
}
return avail + len;//场景④x是这里的avail + len
}
return avail;
}
///一次只能将一个字节数据推回byte[] buf(用于返回的字节数组缓冲区)
public void unread(int b) throws IOException {
ensureOpen();
if (pos == 0) {//pos=表示byte[]0时 buf(用于返回的字节数组缓冲区)已经没有足够的容量再放置数据,所以抛出一个IOException异常。
throw new IOException("Push back buffer is full");
}
buf[--pos] = (byte)b;
}
//回推byte[] b字节数组中[off,off+len)len字节数据在索引位置到byte[] buf(字节数组缓冲区用于回退)
public void unread(byte[] b, int off, int len) throws IOException {
ensureOpen();
if (len > pos) (/如果byte[] buf(字节数组缓冲区用于回退)如果len字节放置不足,则抛出IOExceeption
throw new IOException("Push back buffer is full");
}
pos -= len;/如果byte[] buflen字节(用于回退的字节数组缓冲区)如果有足够的位置放置,则使用system.arraycopy()函数返回
System.arraycopy(b, off, buf, pos, len);
}
public void unread(byte[] b) throws IOException {
unread(b, 0, b.length);
}
//返回byte[] buf(用于回退的字节数组缓冲区)+可用于装饰输入流中的字节总数
public int available() throws IOException {
ensureOpen();
int n = buf.length - pos;byte[] buf(用于回退的字节数组缓冲区)可用于字节总数
int avail = super.available();////重新计算可用于装饰输入流中的字节总数
return n > (Integer.MAX_VALUE - avail)
? Integer.MAX_VALUE
: n + avail;//byte[] buf(用于回退字节数组缓冲区)可用于字节总数+可用于装饰输入流的字节总数
}
//从byte[] buf(用于回退的字节数组缓冲区)+在装饰的输入流中跳过n个字节,如果byte[] buf(用于回退的字节数组缓冲区)+装饰输入流中的字节数<n,返回实际跳过的字节数量
public long skip(long n) throws IOException {
ensureOpen();
if (n <= 0) {
return 0;
}
long pskip = buf.length - pos;//从byte[] buf(用于返回的字节数组缓冲区)跳过的字节
if (pskip > 0) {
if (n < pskip) {
pskip = n;
}
pos += pskip;
n -= pskip;
}
if (n > 0) {
pskip += super.skip(n);///从被装饰的输入流中跳过的字节累积到byte[] buf(用于返回的字节数组缓冲区)跳过的字节
}
return pskip;
}
public boolean markSupported() {
return false;
}
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
///关闭装饰输入流和字节数组缓冲区,用于返回
public synchronized void close() throws IOException {
if (in == null)
return;
in.close();
in = null;
buf = null;
}
}
1.2、PushbackinputStreamread()函数和unread()函数
package java.io;
public class PushbackInputStream extends FilterInputStream {
字节数组缓冲区有限长度,默认长度为1
protected byte[] buf;
///可读指针,byte[] buf指针(包括指针)索引后的所有字节(有限长度的字节数组缓冲区)都可以读取
protected int pos;
...省略部分代码...
///尽量从byte[] buf(用于回退字节数组缓冲区)和装饰输入流中读取len字节至byte[] b的[off,off+len)索引位置分为以下五种场景:
//①、如果byte[] buf(用于返回的字节数组缓冲区)如果有len字节,从缓冲区读取len字节到字节数组byte[] b的[off,off+len)索引位置
//②、如果byte[] buf(用于回退字节数组缓冲区)如果没有字节,且装饰输入流中有len字节,则从装饰输入流中读取len字节至字节数组byte[] b的[off,off+len)索引位置
//③、如果byte[] buf(用于回退的字节数组缓冲区)没有字节,装饰的输入流只有avail(avail<len)个字节,然后从被装饰的输入流中读取avail字节到字节数组byte[] b的[off,off+avail)索引位置
//④、如果byte[] bufavail(用于回退的字节数组缓冲区)(avail<len)如果是字节,请阅读avail字节,剩余的len-avail字节从装饰输入流中读取。如果装饰输入流中没有len-avail字节,则从装饰输入流中读取多少,直到装饰输入流读取,然后将以上两个地方读取的所有字节(如果有x个)放入字节数组byte[](装饰输入流+回退字节数组缓冲区) b的[off,off+x)索引位置
//⑤、如果byte[] buf(用于返回的字节数组缓冲区)和装饰输入流中没有字节的,返回-1
public int read(byte[] b, int off, int len) throws IOException {
///检查装修输入流是否关闭
ensureOpen();
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {//相当于off + len > b.length(我没有看到源码中这样写代码的好处)
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;//从Pushbackinputstreama len个字节==0时读取对象,返回0
}
int avail = buf.length - pos;buf实际上装载在用于回退的字节数组缓冲区.length - pos字节
if (avail > 0) {
if (len < avail) {
avail = len;
}
System.arraycopy(buf, pos, b, off, avail);
pos += avail;
off += avail;
len -= avail;
}
if (len > 0) {
len = super.read(b, off, len);
if (len == -1) {
return avail == 0 ? -1 : avail;
}
return avail + len;//场景④x是这里的avail + len
}
return avail;
}
//回推byte[] b字节数组中[off,off+len)len字节数据在索引位置到byte[] buf(字节数组缓冲区用于回退)
public void unread(byte[] b, int off, int len) throws IOException {
ensureOpen();
if (len > pos) (/如果byte[] buflen字节(用于回退字节数组缓冲区)没有足够的位置放置,抛出IOException
throw new IOException("Push back buffer is full");
}
pos -= len;/如果byte[] buflen字节(用于回退的字节数组缓冲区)如果有足够的位置放置,则使用system.arraycopy()函数返回
System.arraycopy(b, off, buf, pos, len);
}
...省略部分代码...
}
如果用户使用的装饰输入流是 ByteArrayInputStream,然后执行Pushbackinputstream的read()函数和unread()函数时,如下代码:
package com.chelong.bio;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
public class PushbackInputStreamTest {
public static void main(String[] args) throws IOException {
String str = "Hello,World";
InputStream inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
//构建回退流
PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 8);
int len = -1;
System.out.println(“输出内容:”);
while ((len = pushbackInputStream.read()) != -1) {
///转向char类型
char c = (char) len;
if (c == ',') {
//为 ,号时 ,先往前读三个,再倒两个
byte[] b1 = new byte[3];
pushbackInputStream.read(b1);
//后倒两个
pushbackInputStream.unread(b1, 0, 2);
} else {
System.out.print(c);
}
}
}
}
上述代码的执行结果如下:
上述代码的整个执行过程分为以下五个步骤:
①、构建一个长度为8的byte[],通过构建函数 buf(用于回退的字节数组缓冲区)和BytearayInputstream.装饰class类型的输入流如下:
PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 8);

②、按顺序从BytearayInputstreamm.在class类型的输入流中读取字节,直到读取到‘,’,如下所示:
while ((len = pushbackInputStream.read()) != -1) {
///转向char类型
char c = (char) len;
if (c == ',') {
} else {
System.out.print(c);
}
}

输出如下:
Hello
③、读取后,从被装饰的输入流BytearayInputstreamm.byte[]在class中 在B1字节数组中读取3个字节,如下所示:
//为 ,号时 ,先往前读三个,再往后倒两个
byte[] b1 = new byte[3];
pushbackInputStream.read(b1);

④、将步骤③中读入byte[] 在PushbackInputstream中读取byte[0,2)索引位置的数据 buf(用于返回的字节数组缓冲区)的[6,8)索引位置如下:
//后倒两个
pushbackInputStream.unread(b1, 0, 2);

⑤、再次重复执行步骤②按顺序从BytearayInputstreamm.在Class类型的输入流中读取字节时,首先在PushbackInputstream中读取byte[] buf(用于回退字节数组缓冲区)的[6,8)索引位置,然后从BytearayInputStream.在class类型的输入流中读取剩余字节,如下所示:
while ((len = pushbackInputStream.read()) != -1) {
//转换为char类型
char c = (char) len;
if (c == ',') {
} else {
System.out.print(c);
}
}

Wold
二、Streamtokenizer源码
虽然Streamtokenizer不继承InputStreamm.class或OutputStream.class,但其构造函数只能传输到InputStream.class或Reader.class类型的变量非常合适,包括在库的IO部分。Streamtokenizer类用于将任何Inputstream分为一系列“Token"(标记)。这些"Token“(标记)实际上是一些间歇性的文本块,可以用用用户选择的任何东西来分隔。
StreamTokenizer.class UML关系图如下:

StreamTokenizer.class的源代码如下:
package java.io;
import java.util.Arrays;
public class StreamTokenizer {
///内部声明了Reader对象句柄和InputStream对象句柄,用于接收读取流。
private Reader reader = null;
private InputStream input = null;
///声明char类型的数组,初始容量为20,用于存储读取时标记的内容,读取时可根据实际需要自动扩展。
private char buf[] = new char[20];
///声明了int变量peekc。当调用nextoken方法时,peekc用于判断是否需要继续读取下一个字符并将其放入标记中。初始化时,赋值为need_CHAR。
private int peekc = NEED_CHAR;
//定义了两个常量,NEED_CHAR和SKIP_LF都说要读下一个字符,但如果后者遇到‘\\n将其丢弃,然后读取下一个字符。
private static final int NEED_CHAR = Integer.MAX_VALUE;
private static final int SKIP_LF = Integer.MAX_VALUE - 1;
//声明一个boolean变量pushedBack,该变量用于控制执行nexttoken方法时是否需要返回。
private boolean pushedBack;
///声明了一个boolean变量forcelower,用于控制sval是否需要小写。
private boolean forceLower;
///声明一个int变量,用于记录最后一次读取标记时的行数。
private int LINENO = 1;
private boolean eolIsSignificantP = false;
private boolean slashSlashCommentsP = false;
private boolean slashStarCommentsP = false;
///声明数组作为语法表,存储多种类型,依次为空格、数字、字母、引号、注释等类型。
private byte ctype[] = new byte[256];
private static final byte CT_WHITESPACE = 1;
private static final byte CT_DIGIT = 2;
private static final byte CT_ALPHA = 4;
private static final byte CT_QUOTE = 8;
private static final byte CT_COMMENT = 16;
///声明int变量,表示当前标记的标记类型,初始化为TT_NOTHING类型。
public int ttype = TT_NOTHING;
//定义了一个常量,说明此时已经读到了流的末尾。
public static final int TT_EOF = -1;
//定义了一个常量,说明此时已经读到了一行的末尾。
public static final int TT_EOL = '\n';
//定义常量,表示此时读到的标记为数字标记。
public static final int TT_NUMBER = -2;
//定义常量,表示此时读到的标记为文本标记。
public static final int TT_WORD = -3;
//定义了一个常量,表示此时没有标记读取,用于初始化ttype。
private static final int TT_NOTHING = -4;
///声明字符串变量sval,如果当前标记为字符串,则此时将当前标记的值赋予sval。
public String sval;
///声明double变量nval,如果当前标记为值,则此时将当前标记值赋值nval。
public double nval;
/**
* 用于初始化内置语法表,即ctype数组的私有构造函数。
*/
private StreamTokenizer() {
wordChars('a', 'z');
wordChars('A', 'Z');
wordChars(128 + 32, 255);
whitespaceChars(0, ' ');
commentChar('/');
quoteChar('"');
quoteChar(\'');
parseNumbers();
}
/**
* 已废弃
* 一个带有参数的构造函数,引入的参数是InputStream对象,首先对其进行安全检测,如果不是null,则赋予InputStream对象句柄,input。值得注
* 这意味着这种方法现在已经被抛弃了。
*/
@Deprecated
public StreamTokenizer(InputStream is) {
this();
if (is == null) {
throw new NullPointerException();
}
input = is;
}
/**
*一个带有参数的构造函数,输入的参数是一个Reader对象,首先进行安全检测,如果不是null,则赋值给Reader对象的句柄,reader。
*/
public StreamTokenizer(Reader r) {
this();
if (r == null) {
throw new NullPointerException();
}
reader = r;
}
/**
* 该方法用于重置标记的语法表,通过一个循环将语法表中的每个元素放置为0,即作为普通字符处理。
*/
public void resetSyntax() {
for (int i = ctype.length; --i >= 0;)
ctype[i] = 0;
}
/**
* 用于初始化语法表的两个参数是语法表的前后区间,将数据传输到该区间
*/
public void wordChars(int low, int hi) {
if (low < 0)
low = 0;
if (hi >= ctype.length)
hi = ctype.length - 1;
while (low <= hi)
ctype[low++]
|= CT_ALPHA;
}
/**
* 用于初始化语法表的两个参数是语法表的前后区间,将传入区间的数据视为空白空间。
*/
public void whitespaceChars(int low, int hi) {
if (low < 0)
low = 0;
if (hi >= ctype.length)
hi = ctype.length - 1;
while (low <= hi)
ctype[low++] = CT_WHITESPACE;
}
/**
* 用于初始化语法表,传入的两个参数,是语法表的前后间隔,将传入间隔的数据作为普通字符处理。
*/
public void ordinaryChars(int low, int hi) {
if (low < 0)
low = 0;
if (hi >= ctype.length)
hi = ctype.length - 1;
while (low <= hi)
ctype[low++] = 0;
}
/**
* 用于初始化语法表,将相应的类型改为0,通过引入的参数作为语法表的索引,作为普通字符处理。
*/
public void ordinaryChar(int ch) {
if (ch >= 0 && ch < ctype.length)
ctype[ch] = 0;
}
/**
* 用于初始化语法表,以引入的int型值为索引,将相应的数组划分为CT_COMMENT注释型。
*/
public void commentChar(int ch) {
if (ch >= 0 && ch < ctype.length)
ctype[ch] = CT_COMMENT;
}
/**
* 用于初始化语法表,以引入的int型值为索引,将相应的数组划分为CT_QUOTE引用型。
*/
public void quoteChar(int ch) {
if (ch >= 0 && ch < ctype.length)
ctype[ch] = CT_QUOTE;
}
/**
* 将数字0-9用于初始化语法表,.分为CT_DIGIT数字类型。
*/
public void parseNumbers() {
for (int i = '0'; i <= '9'; i++)
ctype[i] |= CT_DIGIT;
ctype['.'] |= CT_DIGIT;
ctype['-'] |= CT_DIGIT;
}
/**
* 该方法用于设置eolissignificant变量值,用于恒定是否将行的结尾作为标记。
*/
public void eolIsSignificant(boolean flag) {
eolIsSignificantP = flag;
}
/**
* 该方法用于设置slashstarcommnetsp的值,用于恒定是否将c语言注释作为特殊字符。如果是true,所有包含在注释中的内容都将被丢弃。为false,则
* 作为普通字符处理。
*/
public void slashStarComments(boolean flag) {
slashStarCommentsP = flag;
}
/**
* 该方法与上一种方法相似,但用于恒定是否认可c++形式的注释。
*/
public void slashSlashComments(boolean flag) {
slashSlashCommentsP = flag;
}
/**
* 该方法用于修改forcelower变量的值。
*/
public void lowerCaseMode(boolean fl) {
forceLower = fl;
}
/**
* 定义read函数实际上是通过调用内置reader/input 从read函数中可以看出,优先级是使用reader读取。
*/
private int read() throws IOException {
if (reader != null)
return reader.read();
else if (input != null)
return input.read();
else
throw new IllegalStateException();
}
/**
* 该函数用于获取下一个标记。
*/
public int nextToken() throws IOException {
///判断是否需要返回。如果pushedBack值为true,则直接返回上一个标记类型,并将pushedBack值重置为false。
if (pushedBack) {
pushedBack = false;
return ttype;
}
byte ct[] = ctype;
sval = null;
int c = peekc;
if (c < 0)
c = NEED_CHAR;
if (c == SKIP_LF) {
c = read();
if (c < 0)
return ttype = TT_EOF;
if (c == '\n')
c = NEED_CHAR;
}
if (c == NEED_CHAR) {
c = read();
if (c < 0)
return ttype = TT_EOF;
}
ttype = c; /* Just to be safe */
peekc = NEED_CHAR;///重置peekc,方便下次进入方法时使用
///如果当前类型为空格,则操作
int ctype = c < 256 ? ct[c] : CT_ALPHA;
while ((ctype & CT_WHITESPACE) != 0) {
if (c == '\r') {
LINENO++;
if (eolIsSignificantP) {
peekc = SKIP_LF;
return ttype = TT_EOL;
}
c = read();
if (c == '\n')
c = read();
} else {
if (c == '\n') {
LINENO++;
if (eolIsSignificantP) {
return ttype = TT_EOL;
}
}
c = read();
}
if (c < 0)
return ttype = TT_EOF;
ctype = c < 256 ? ct[c] : CT_ALPHA;
}
///如果当前类型的数字操作
if ((ctype & CT_DIGIT) != 0) {
boolean neg = false;
if (c == '-') {
c = read();
if (c != '.' && (c < '0'
|| c > '9')) {
peekc = c;
return ttype = '-';
}
neg = true;
}
double v = 0;
int decexp = 0;
int seendot = 0;
while (true) {
if (c == '.' && seendot == 0)
seendot = 1;
else if ('0' <= c && c <= '9') {
v = v * 10 + (c - '0');
decexp += seendot;
} else
break;
c = read();
}
peekc = c;
if (decexp != 0) {
double denom = 10;
decexp--;
while (decexp > 0) {
denom *= 10;
decexp--;
}
/* Do one pision of a likely-to-be-more-accurate number */
v = v / denom;
}
nval = neg ? -v : v;
return ttype = TT_NUMBER;
}
///如果当前类型的字母符号操作
if ((ctype & CT_ALPHA) != 0) {
int i = 0;
do {
if (i >= buf.length) {
buf = Arrays.copyOf(buf, buf.length * 2);///自动扩容
}
buf[i++] = (char) c;
c = read();
ctype = c < 0 ?= 0) {
int i = 0;
do {
if (i >= buf.length) {
buf = Arrays.copyOf(buf, buf.length * 2);///自动扩容
}
buf[i++] = (char) c;
c = read();
ctype = c < 0 ? CT_WHITESPACE : c < 256 ? ct[c] : CT_ALPHA;
} while ((ctype & (CT_ALPHA | CT_DIGIT)) != 0);
peekc = c;
sval = String.copyValueOf(buf, 0, i);
if (forceLower)
sval = sval.toLowerCase();
return ttype = TT_WORD;
}
///如果当前类型是引用符号的操作
if ((ctype & CT_QUOTE) != 0) {
ttype = c;
int i = 0;
/* Invariants (because \Octal needs a lookahead):
* (i) c contains char value
* (ii) d contains the lookahead
*/
int d = read();
while (d >= 0 && d != ttype && d != '\n' && d != '\r') {
if (d == '\\') {
c = read();
int first = c; /* To allow \377, but not \477 */
if (c >= '0' && c <= '7') {
c = c - '0';
int c2 = read();
if ('0' <= c2 && c2 <= '7') {
c = (c << 3) + (c2 - '0');
c2 = read();
if ('0' <= c2 && c2 <= '7' && first <= '3') {
c = (c << 3) + (c2 - '0');
d = read();
} else
d = c2;
} else
d = c2;
} else {
c = switch (c) {
case 'a' -> 0x7;
case 'b' -> '\b';
case 'f' -> 0xC;
case 'n' -> '\n';
case 'r' -> '\r';
case 't' -> '\t';
case 'v' -> 0xB;
default -> c;
};
d = read();
}
} else {
c = d;
d = read();
}
if (i >= buf.length) {
buf = Arrays.copyOf(buf, buf.length * 2);
}
buf[i++] = (char)c;
}
peekc = (d == ttype) ? NEED_CHAR : d;
sval = String.copyValueOf(buf, 0, i);
return ttype;
}
//处理注释形式。 NEED_CHAR : d;
sval = String.copyValueOf(buf, 0, i);
return ttype;
}
//处理注释形式。
if (c == '/' && (slashSlashCommentsP || slashStarCommentsP)) {
c = read();
if (c == '*' && slashStarCommentsP) {
int prevc = 0;
while ((c = read()) != '/' || prevc != '*') {
if (c == '\r') {
LINENO++;
c = read();
if (c == '\n') {
c = read();
}
} else {
if (c == '\n') {
LINENO++;
c = read();
}
}
if (c < 0)
return ttype = TT_EOF;
prevc = c;
}
return nextToken();
} else if (c == '/' && slashSlashCommentsP) {
while ((c = read()) != '\n' && c != '\n' && c != '\r' && c >= 0);
peekc = c;
return nextToken();
} else {
/* Now see if it is still a single line comment */
if ((ct['/'] & CT_COMMENT) != 0) {
while ((c = read()) != '\n' && c != '\r' && c >= 0);
peekc = c;
return nextToken();
} else {
peekc = c;
return ttype = '/';
}
}
}
///当前类型是注释时的操作。
if ((ctype & CT_COMMENT) != 0) {
while ((c = read()) != '\n' && c != '\r' && c >= 0);
peekc = c;
return nextToken();
}
return ttype = c;
}
/**
* 调用此函数时,如果ttype不是tt_,则首先进行安全检测NOTHING,也就是说,已经调用了nextoeken函数,然后将pushedback的值设置为true,下次执行nextoeken函数时,
* 不会修改当前标记的类型,也不会修改当前nval或sval的值。
*/
public void pushBack() {
if (ttype != TT_NOTHING) /* No-op if nextToken() not called */
pushedBack = true;
}
/**
* 该函数返回LINENO的值,即分割标记后的最终行数。值得注意的是,如果将换行符设置为普通字符,则会影响函数的准确性。
*/
public int lineno() {
return LINENO;
}
/**
* 这个函数可以得到一个字符串,字符串的内容是当前标记的类型和行数。
*/
public String toString() {
String ret = switch (ttype) {
case TT_EOF -> "EOF";
case TT_EOL -> "EOL";
case TT_WORD -> sval;
case TT_NUMBER -> "n=" + nval;
case TT_NOTHING -> "NOTHING";
default -> {
if (ttype < 256 && ((ctype[ttype] & CT_QUOTE) != 0)) {
yield sval;
}
char s[] = new char[3];
s[0] = s[2] = '\'';
s[1] = (char) ttype;
yield new String(s);
}
};
return "Token[" + ret + "], line " + LINENO;
}
}
2.1、Streamtokenize的两种使用方法
2.1.1、“(英文单引号)分析空间、//(反斜杠)
我的windows操作系统D盘下有一个Streamtokenizer.txt文件,如下所示:

您可以使用FileReader读取此文件,然后使用StreamTokenizer读取该文件中的每个token和token对应的行号。
import java.io.*;
public class StreamTokenizerTest {
public static void main(String[] args) throws UnsupportedEncodingException,
FileNotFoundException {
///通过输入Filereader构建Streamtokenizer。本地txt文件是在这里读取的。
StreamTokenizer stk = new StreamTokenizer(new FileReader(new File(
"D:\\StreamTokenizer.txt")));
try {
///不读取文件结尾时,不断调用nextoken方法,然后打印每个token及其行号。
while (stk.nextToken() != StreamTokenizer.TT_EOF) {
String s = null;
switch (stk.ttype) {
case StreamTokenizer.TT_WORD:
s = stk.sval;
break;
case StreamTokenizer.TT_NUMBER:
s = String.valueOf(stk.nval);
break;
default:
s = stk.sval;
}
System.out.println(stk.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码的执行结果如下:

从结果可以看出,通过nextoken()函数读取的数字数据都是double类型,如果不符合要求,需要自行转换。streamtokenizer将双引号“”中的内容作为token处理,并将//后的内容作为注释(注释不会作为token读取)。例如,修改上述D盘下的streamtokenizer.txt文件如下所示:

再次执行上述StreamTokenizerTest.class,结果如下:

如果你想把这些符号作为普通符号来处理,只是Streamtokenize需要调用.class::ordinaryChar()函数可以将特殊字符作为普通字符处理,如修改上述Streamtokenizertestesteste.class,修改后如下:
import java.io.*;
public class StreamTokenizerTest {
public static void main(String[] args) throws UnsupportedEncodingException,
FileNotFoundException {
///通过输入Filereader构建Streamtokenizer。本地txt文件是在这里读取的。
StreamTokenizer stk = new StreamTokenizer(new FileReader(new File(
"D:\\StreamTokenizer.txt")));
stk.ordinaryChar(\);\\ \表示转义
stk.ordinaryChar('/');\\ /不需要转义
try {
///不读取文件结尾时,不断调用nextoken方法,然后打印每个token及其行号。
while (stk.nextToken() != StreamTokenizer.TT_EOF) {
String s = null;
switch (stk.ttype) {
case StreamTokenizer.TT_WORD:
s = stk.sval;
break;
case StreamTokenizer.TT_NUMBER:
s = String.valueOf(stk.nval);
break;
default:
s = stk.sval;
}
System.out.println(stk.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在D盘下继续读取StreamTokenizer.txt文件,如下所示:

上述代码的执行结果如下:

Streamtokenize也可以使用.class::resetSyntax()函数将每个ASCII码表示的字符和中文字符串作为一个token处理,例如修改上述Streamtokenizertesteste.class,修改后如下:
import java.io.*;
public class StreamTokenizerTest {
public static void main(String[] args) throws UnsupportedEncodingException,
FileNotFoundException {
///通过输入Filereader构建Streamtokenizer。本地txt文件是在这里读取的。
StreamTokenizer stk = new StreamTokenizer(new FileReader(new File(
"D:\\StreamTokenizer.txt")));
stk.resetSyntax();
try {
///不读取文件结尾时,不断调用nextoken方法,然后打印每个token及其行号。
while (stk.nextToken() != StreamTokenizer.TT_EOF) {
String s = null;
switch (stk.ttype) {
case StreamTokenizer.TT_WORD:
s = stk.sval;
break;
case StreamTokenizer.TT_NUMBER:
s = String.valueOf(stk.nval);
break;
default:
s = stk.sval;
}
System.out.println(stk.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在D盘下继续读取Streamtokenizer.txt文件,如下所示:

上述代码的执行结果如下:

代码如下所示:
import java.io.*;
public class StreamTokenizerTest {
public static void main(String[] args) throws IOException {
///将标准输入流传到Streamtokenizer中。
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int a, b;
while (in.nextToken() != StreamTokenizer.TT_EOF) {
a = (int) in.nval;
in.nextToken();
b = (int) in.nval;
//out.println(a + b);
System.out.println("a + b = " + (a + b));
}
//真实地写出缓存区内的数据。
out.flush();
}
}
上述代码的执行结果如下:

参考资料: https://www.tulingxueyuan.cn/d/file/p/20260518/kgqkadl0eqc.html https://www.tulingxueyuan.cn/d/file/p/20260518/kowc1biu3nh https://www.oschina.net/uploads/doc/javase-6-doc-api-zh_CN/java/io/StreamTokenizer.html