13、PushbackInputStream和StreamTokenizer的源码分析和利用方法具体分析

[复制链接]
发表于 3 天前 | 显示全部楼层 |阅读模式
一、PushbackInputStream源码——可以对输入Stream举行回退的装饰器类

  PushbackInputStream恰当语法剖析过程中的语法回退,由于这个类提供了有限字节(内部界说了一个默认长度为1的byte[] buf字节数组)的缓冲式回退本事,具体过程如下:
①、当调用unread()函数时会将恣意字节(可以是从被装饰的输入流中读取的字节,也可以是本身界说的字节)压入byte[] buf字节数组的头部;
②、当后续调用read()函数时优先读取这个byte[] buf字节数组中被压入的字节;
当利用PushbackInputStream举行语法剖析时,须要注意 unread()函数的调用次序、EOF 处置惩罚及嵌套回退风险等。
  由于语法剖析器常须要先预读一个字符判定范例,假如发现不是目的范例再退归去,而 InputStream.class 本身不支持回退,以是PushbackInputStream.class就是为此筹划的。
  许多语法剖析须要预读多个字符才气确定 token 范例,好比辨认 == 和 =、或 /* 解释起始符。PushbackInputStream默认构造函数只分配 1 字节缓冲(内部界说了一个默认长度为1的byte[] buf字节数组),根本不敷用,因此须要利用
  1. new PushbackInputStream(in, 4)
复制代码
构造一个长度为4的byte[] buf字节数组作为缓冲区用来覆盖大多数双字符操纵符和简朴分隔符场景,假如要支持 Unicode 转义(如 \u0061)或长标识符前缀判定,缓冲区需更大,但别盲目设成 1024,同时缓冲区byte[] buf字节数组的长度在构造后不可变,运行时并无法扩容。好比下面是一个辨认数字字面量(含小数点)时的安全回退示例,伪代码如下所示:
  1. ...省略部分代码...
  2. int ch = in.read();
  3. if (ch == '.') {
  4.     int next = in.read();
  5.     if (Character.isDigit(next)) {
  6.         // 确认是小数,继续解析
  7.         parseFractionPart();
  8.     } else {
  9.         // 不是小数,退回两个字符:'.' 和 next
  10.         in.unread(next);
  11.         in.unread('.');
  12.     }
  13. } else {
  14.     // 其他情况按原逻辑处理
  15. }
  16. ...省略部分代码...
复制代码
1.1、PushbackInputStream的源码分析

  PushbackInputStream.class 的UML关系图,如下所示:

  PushbackInputStream.class的源码,如下所示:
  1. package java.io;
  2. public class PushbackInputStream extends FilterInputStream {
  3.     //有限长度的用于回退的字节数组缓冲区,默认长度为1
  4.     protected byte[] buf;
  5.     //可读指针,byte[] buf(有限长度的用于回退的字节数组缓冲区)中该指针(包括该指针)索引之后的所有字节都可以读
  6.     protected int pos;
  7.     //检查被装饰的输入流是否关闭
  8.     private void ensureOpen() throws IOException {
  9.         if (in == null)
  10.             throw new IOException("Stream closed");
  11.     }
  12.     //构造函数,in为被装饰的输入流,size为byte[] buf(有限长度的用于回退的字节数组缓冲区)的长度
  13.     public PushbackInputStream(InputStream in, int size) {
  14.         super(in);
  15.         if (size <= 0) {
  16.             throw new IllegalArgumentException("size <= 0");
  17.         }
  18.         this.buf = new byte[size];
  19.         this.pos = size;//将可读指针指向byte[] buf(有限长度的用于回退的字节数组缓冲区)中最后一个索引(size-1)之后
  20.     }
  21.     //构造函数,in为被装饰的输入流
  22.     public PushbackInputStream(InputStream in) {
  23.         this(in, 1);//构造一个默认长度为1的byte[] buf(用于回退的字节数组缓冲区)
  24.     }
  25.     //如果byte[] buf(用于回退的字节数组缓冲区)中有可读的字节的话,就从该缓冲区中读取1个字节
  26.     //如果byte[] buf(用于回退的字节数组缓冲区)中没有可读的字节的话,就从被装饰的输入流中读取1个字节
  27.     //如果byte[] buf(用于回退的字节数组缓冲区)和被装饰的输入流中都没有可读的字节的话,返回-1
  28.     public int read() throws IOException {
  29.         ensureOpen();
  30.         if (pos < buf.length) {
  31.             return buf[pos++] & 0xff;
  32.         }
  33.         return super.read();
  34.     }
  35.     //尽可能的从byte[] buf(用于回退的字节数组缓冲区)和被装饰的输入流中读取len个字节到byte[] b的[off,off+len)索引位置,总共分为以下5种场景:
  36.     //①、如果byte[] buf(用于回退的字节数组缓冲区)中有len个字节的话,就从该缓冲区中读取len个字节到字节数组byte[] b的[off,off+len)索引位置
  37.     //②、如果byte[] buf(用于回退的字节数组缓冲区)中没有任何字节并且被装饰的输入流中有len个字节,那就从被装饰的输入流中读取len个字节到字节数组byte[] b的[off,off+len)索引位置
  38.     //③、如果byte[] buf(用于回退的字节数组缓冲区)中没有任何字节并且被装饰的输入流中只有avail(avail<len)个字节,那就从被装饰的输入流中读取avail个字节到字节数组byte[] b的[off,off+avail)索引位置
  39.     //④、如果byte[] buf(用于回退的字节数组缓冲区)中有avail(avail<len)个字节的话,就读取avail个字节,剩余len-avail个字节从被装饰的输入流中读取,如果被装饰的输入流中没有len-avail个字节的话,那就从被装饰的输入流中有多少读取多少,直到将被装饰的输入流读取完毕,然后将以上2个地方(被装饰的输入流+用于回退的字节数组缓冲区)读取的所有字节(假如有x个)放入到字节数组byte[] b的[off,off+x)索引位置
  40.     //⑤、如果byte[] buf(用于回退的字节数组缓冲区)和被装饰的输入流中都没有任何字节的话,返回-1
  41.     public int read(byte[] b, int off, int len) throws IOException {
  42.         //检查被装饰的输入流是否关闭
  43.         ensureOpen();
  44.         if (b == null) {
  45.             throw new NullPointerException();
  46.         } else if (off < 0 || len < 0 || len > b.length - off) {//相当于off + len > b.length(源码中这样写代码的好处我没看出来)
  47.             throw new IndexOutOfBoundsException();
  48.         } else if (len == 0) {
  49.             return 0;//要从PushbackInputStream 对象中读取的len个字节==0时,返回0
  50.         }
  51.         int avail = buf.length - pos;//用于回退的字节数组缓冲区中实际装载了buf.length - pos个字节
  52.         if (avail > 0) {
  53.             if (len < avail) {
  54.                 avail = len;
  55.             }
  56.             System.arraycopy(buf, pos, b, off, avail);
  57.             pos += avail;
  58.             off += avail;
  59.             len -= avail;
  60.         }
  61.         if (len > 0) {
  62.             len = super.read(b, off, len);
  63.             if (len == -1) {
  64.                 return avail == 0 ? -1 : avail;
  65.             }
  66.             return avail + len;//场景④中的x就是这里的avail + len
  67.         }
  68.         return avail;
  69.     }
  70.     //一次只可以回推1个字节数据到byte[] buf(用于回退的字节数组缓冲区)中
  71.     public void unread(int b) throws IOException {
  72.         ensureOpen();
  73.         if (pos == 0) {//pos=0时,表示byte[] buf(用于回退的字节数组缓冲区)中已经没有足够的容量再放置数据,所以抛出一个IOException异常。
  74.             throw new IOException("Push back buffer is full");
  75.         }
  76.         buf[--pos] = (byte)b;
  77.     }
  78.     //一次回推byte[] b字节数组中[off,off+len)索引位置的len个字节数据到byte[] buf(用于回退的字节数组缓冲区)中
  79.     public void unread(byte[] b, int off, int len) throws IOException {
  80.         ensureOpen();
  81.         if (len > pos) {//如果byte[] buf(用于回退的字节数组缓冲区)中没有足够的位置放置len个字节,则抛出一个IOException
  82.             throw new IOException("Push back buffer is full");
  83.         }
  84.         pos -= len;//如果byte[] buf(用于回退的字节数组缓冲区)中有足够的位置放置len个字节,则使用System.arraycopy()函数进行回退
  85.         System.arraycopy(b, off, buf, pos, len);
  86.     }
  87.     public void unread(byte[] b) throws IOException {
  88.         unread(b, 0, b.length);
  89.     }
  90.     //返回byte[] buf(用于回退的字节数组缓冲区)+被装饰的输入流中可以被使用的字节总数量
  91.     public int available() throws IOException {
  92.         ensureOpen();
  93.         int n = buf.length - pos;//先计算用于byte[] buf(用于回退的字节数组缓冲区)中可以被使用的字节总数量
  94.         int avail = super.available();//再计算被装饰的输入流中可以被使用的字节总数量
  95.         return n > (Integer.MAX_VALUE - avail)
  96.                     ? Integer.MAX_VALUE
  97.                     : n + avail;//byte[] buf(用于回退的字节数组缓冲区)中可以被使用的字节总数量+被装饰的输入流中可以被使用的字节总数量
  98.     }
  99.     //从byte[] buf(用于回退的字节数组缓冲区)+被装饰的输入流中跳过n个字节,如果byte[] buf(用于回退的字节数组缓冲区)+被装饰的输入流中的字节数量<n,则返回实际跳过的字节数量
  100.     public long skip(long n) throws IOException {
  101.         ensureOpen();
  102.         if (n <= 0) {
  103.             return 0;
  104.         }
  105.         long pskip = buf.length - pos;//从byte[] buf(用于回退的字节数组缓冲区)中跳过的字节
  106.         if (pskip > 0) {
  107.             if (n < pskip) {
  108.                 pskip = n;
  109.             }
  110.             pos += pskip;
  111.             n -= pskip;
  112.         }
  113.         if (n > 0) {
  114.             pskip += super.skip(n);//从被装饰的输入流中跳过的字节累加到从byte[] buf(用于回退的字节数组缓冲区)中跳过的字节
  115.         }
  116.         return pskip;
  117.     }
  118.     public boolean markSupported() {
  119.         return false;
  120.     }
  121.     public synchronized void mark(int readlimit) {
  122.     }
  123.     public synchronized void reset() throws IOException {
  124.         throw new IOException("mark/reset not supported");
  125.     }
  126.     //关闭被装饰的输入流和用于回退的字节数组缓冲区
  127.     public synchronized void close() throws IOException {
  128.         if (in == null)
  129.             return;
  130.         in.close();
  131.         in = null;
  132.         buf = null;
  133.     }
  134. }
复制代码
1.2、PushbackInputStream的read()函数和unread()函数
  1. package java.io;
  2. public class PushbackInputStream extends FilterInputStream {
  3.     //有限长度的用于回退的字节数组缓冲区,默认长度为1
  4.     protected byte[] buf;
  5.     //可读指针,byte[] buf(有限长度的用于回退的字节数组缓冲区)中该指针(包括该指针)索引之后的所有字节都可以读
  6.     protected int pos;
  7.    
  8.     ...省略部分代码...
  9.     //尽可能的从byte[] buf(用于回退的字节数组缓冲区)和被装饰的输入流中读取len个字节到byte[] b的[off,off+len)索引位置,总共分为以下5种场景:
  10.     //①、如果byte[] buf(用于回退的字节数组缓冲区)中有len个字节的话,就从该缓冲区中读取len个字节到字节数组byte[] b的[off,off+len)索引位置
  11.     //②、如果byte[] buf(用于回退的字节数组缓冲区)中没有任何字节并且被装饰的输入流中有len个字节,那就从被装饰的输入流中读取len个字节到字节数组byte[] b的[off,off+len)索引位置
  12.     //③、如果byte[] buf(用于回退的字节数组缓冲区)中没有任何字节并且被装饰的输入流中只有avail(avail<len)个字节,那就从被装饰的输入流中读取avail个字节到字节数组byte[] b的[off,off+avail)索引位置
  13.     //④、如果byte[] buf(用于回退的字节数组缓冲区)中有avail(avail<len)个字节的话,就读取avail个字节,剩余len-avail个字节从被装饰的输入流中读取,如果被装饰的输入流中没有len-avail个字节的话,那就从被装饰的输入流中有多少读取多少,直到将被装饰的输入流读取完毕,然后将以上2个地方(被装饰的输入流+用于回退的字节数组缓冲区)读取的所有字节(假如有x个)放入到字节数组byte[] b的[off,off+x)索引位置
  14.     //⑤、如果byte[] buf(用于回退的字节数组缓冲区)和被装饰的输入流中都没有任何字节的话,返回-1
  15.     public int read(byte[] b, int off, int len) throws IOException {
  16.         //检查被装饰的输入流是否关闭
  17.         ensureOpen();
  18.         if (b == null) {
  19.             throw new NullPointerException();
  20.         } else if (off < 0 || len < 0 || len > b.length - off) {//相当于off + len > b.length(源码中这样写代码的好处我没看出来)
  21.             throw new IndexOutOfBoundsException();
  22.         } else if (len == 0) {
  23.             return 0;//要从PushbackInputStream 对象中读取的len个字节==0时,返回0
  24.         }
  25.         int avail = buf.length - pos;//用于回退的字节数组缓冲区中实际装载了buf.length - pos个字节
  26.         if (avail > 0) {
  27.             if (len < avail) {
  28.                 avail = len;
  29.             }
  30.             System.arraycopy(buf, pos, b, off, avail);
  31.             pos += avail;
  32.             off += avail;
  33.             len -= avail;
  34.         }
  35.         if (len > 0) {
  36.             len = super.read(b, off, len);
  37.             if (len == -1) {
  38.                 return avail == 0 ? -1 : avail;
  39.             }
  40.             return avail + len;//场景④中的x就是这里的avail + len
  41.         }
  42.         return avail;
  43.     }
  44.     //一次回推byte[] b字节数组中[off,off+len)索引位置的len个字节数据到byte[] buf(用于回退的字节数组缓冲区)中
  45.     public void unread(byte[] b, int off, int len) throws IOException {
  46.         ensureOpen();
  47.         if (len > pos) {//如果byte[] buf(用于回退的字节数组缓冲区)中没有足够的位置放置len个字节,则抛出一个IOException
  48.             throw new IOException("Push back buffer is full");
  49.         }
  50.         pos -= len;//如果byte[] buf(用于回退的字节数组缓冲区)中有足够的位置放置len个字节,则使用System.arraycopy()函数进行回退
  51.         System.arraycopy(b, off, buf, pos, len);
  52.     }
  53.    
  54.     ...省略部分代码...
  55. }
复制代码
  假如利用者利用的被装饰的输入流是 ByteArrayInputStream,然后实验PushbackInputStream的read()函数和unread()函数时,如下代码:
  1. package com.chelong.bio;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.PushbackInputStream;
  6. public class PushbackInputStreamTest {
  7.     public static void main(String[] args) throws IOException {
  8.         String str = "Hello,World";
  9.         InputStream inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
  10.         //构建回退流
  11.         PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 8);
  12.         int len = -1;
  13.         System.out.println("输出内容:");
  14.         while ((len = pushbackInputStream.read()) != -1) {
  15.             //转为char类型
  16.             char c = (char) len;
  17.             if (c == ',') {
  18.                 //为 ,号时 ,先往前读3个,再往后倒两个
  19.                 byte[] b1 = new byte[3];
  20.                 pushbackInputStream.read(b1);
  21.                 //往后倒两个
  22.                 pushbackInputStream.unread(b1, 0, 2);
  23.             } else {
  24.                 System.out.print(c);
  25.             }
  26.         }
  27.     }
  28. }
复制代码
上面代码的实验效果如下:

  上面代码的整个实验过程分为以下5步:
①、通过构造函数构建一个长度为8的byte[] buf(用于回退的字节数组缓冲区)和ByteArrayInputStream.class范例的被装饰的输入流,如下所示:
  1. PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 8);
复制代码

②、按照次序从ByteArrayInputStream.class范例的输入流中读取字节,直到读取到','时,如下所示:
  1.         while ((len = pushbackInputStream.read()) != -1) {
  2.             //转为char类型
  3.             char c = (char) len;
  4.             if (c == ',') {
  5.                
  6.             } else {
  7.                 System.out.print(c);
  8.             }
  9.         }
复制代码

输出如下:
  1. Hello
复制代码
③、当读取到','之后,从被装饰的输入流ByteArrayInputStream.class中往byte[] b1字节数组中读取3个字节,如下所示:
  1.                 //为 ,号时 ,先往前读3个,再往后倒两个
  2.                 byte[] b1 = new byte[3];
  3.                 pushbackInputStream.read(b1);
复制代码

④、将步调③中读入到byte[] b1字节数组中的[0,2)索引位置的数据读取到PushbackInputStream中的byte[] buf(用于回退的字节数组缓冲区)的[6,8)索引位置中,如下所示:
  1.                 //往后倒两个
  2.                 pushbackInputStream.unread(b1, 0, 2);
复制代码

⑤、再次重复实验步调②中按照次序从ByteArrayInputStream.class范例的输入流中读取字节时,先读取PushbackInputStream中的byte[] buf(用于回退的字节数组缓冲区)的[6,8)索引位置,再从ByteArrayInputStream.class范例的输入流中读取剩余字节,如下所示:
  1.         while ((len = pushbackInputStream.read()) != -1) {
  2.             //转为char类型
  3.             char c = (char) len;
  4.             if (c == ',') {
  5.                
  6.             } else {
  7.                 System.out.print(c);
  8.             }
  9.         }
复制代码
  1. Wold
复制代码
二、StreamTokenizer源码

  只管StreamTokenizer并不是继续了InputStream.class或OutputStream.class,但它的构造函数只能传入InputStream.class大概Reader.class范例的变量,以是非常恰当地包罗在库的IO部分中。StreamTokenizer类用于将任何InputStream分割为一系列的“Token”(暗号)。这些“Token”(暗号)现实是一些断续的文本块,中心可以用利用者选择的任何东西分隔。
StreamTokenizer.class 的UML关系图,如下所示:

  StreamTokenizer.class的源码,如下所示:
  1. package java.io;
  2. import java.util.Arrays;
  3. public class StreamTokenizer {
  4.     //内部声明了一个Reader对象句柄和一个InputStream对象句柄,用于接收读取流。
  5.     private Reader reader = null;
  6.     private InputStream input = null;
  7.     //声明了一个char类型的数组,初始容量为20,用于存储读取时标记的内容,读取时,可以根据实际需要自动扩容。
  8.     private char buf[] = new char[20];
  9.     //声明了一个int型变量peekc,当调用nextToken方法的时候,peekc作为一个状态,用于判断是否需要继续读取下一个字符放入到标记中,初始化时赋值为NEED_CHAR。
  10.     private int peekc = NEED_CHAR;
  11.     //定义了两个常量,NEED_CHAR和SKIP_LF都表示要读取下一个字符,但后者如果遇到一个'\n',则会将它丢弃然后读取下一个字符。
  12.     private static final int NEED_CHAR = Integer.MAX_VALUE;
  13.     private static final int SKIP_LF = Integer.MAX_VALUE - 1;
  14.     //声明了一个boolean型变量pushedBack,该变量用于控制执行nextToken方法时,是否需要进行回退。
  15.     private boolean pushedBack;
  16.     //声明了一个boolean型变量forceLower,该变量用于控制sval是否需要进行小写处理。
  17.     private boolean forceLower;
  18.     //声明了一个int型变量,用于记录最后一次读取标记时的行数。
  19.     private int LINENO = 1;
  20.    
  21.     private boolean eolIsSignificantP = false;
  22.     private boolean slashSlashCommentsP = false;
  23.     private boolean slashStarCommentsP = false;
  24.     //声明了一个数组作为一个语法表,存放几种类型,依次为空格,数字,字母,引号,注解等类型。
  25.     private byte ctype[] = new byte[256];
  26.     private static final byte CT_WHITESPACE = 1;
  27.     private static final byte CT_DIGIT = 2;
  28.     private static final byte CT_ALPHA = 4;
  29.     private static final byte CT_QUOTE = 8;
  30.     private static final byte CT_COMMENT = 16;
  31.     //声明了一个int型变量,表明当前标记的标记类型,初始化时为TT_NOTHING类型。
  32.     public int ttype = TT_NOTHING;
  33.     //定义了一个常量,表示此时已经读取到了流的末尾。
  34.     public static final int TT_EOF = -1;
  35.     //定义了一个常量,表示此时已经读到了一行的末尾。
  36.     public static final int TT_EOL = '\n';
  37.     //定义了一个常量,表示此时读到的标记是一个数字标记。
  38.     public static final int TT_NUMBER = -2;
  39.     //定义了一个常量,表示此时读到的标记是一个文本标记。
  40.     public static final int TT_WORD = -3;
  41.     //定义了一个常量,表示此时并没有进行标记的读取,用于初始化ttype。
  42.     private static final int TT_NOTHING = -4;
  43.     //声明了一个字符串型变量sval,如果当前的标记为字符串,那么此时将当前标记的值赋值给sval。
  44.     public String sval;
  45.     //声明了一个double型变量nval,如果当前的标记为数值,那么此时将当前标记的值赋值给nval。
  46.     public double nval;
  47.     /**
  48.      * 一个私有的构造函数,用于初始化内置的语法表,即ctype数组。
  49.      */
  50.     private StreamTokenizer() {
  51.         wordChars('a', 'z');
  52.         wordChars('A', 'Z');
  53.         wordChars(128 + 32, 255);
  54.         whitespaceChars(0, ' ');
  55.         commentChar('/');
  56.         quoteChar('"');
  57.         quoteChar('\'');
  58.         parseNumbers();
  59.     }
  60.     /**
  61.      * 已废弃
  62.      * 一个带一个参数的构造函数,传入的参数为一个InputStream对象,先对其进行安全检测,如果不为null,则赋值给最初声明的InputStream对象句柄,input。值得注
  63.      * 意的是该方法如今已经被弃用了。
  64.      */
  65.     @Deprecated
  66.     public StreamTokenizer(InputStream is) {
  67.         this();
  68.         if (is == null) {
  69.             throw new NullPointerException();
  70.         }
  71.         input = is;
  72.     }
  73.     /**
  74.      *一个带一个参数的构造函数,传入的参数为一个Reader对象,先对其进行安全检测,如果不为null,则赋值给最初声明的Reader对象句柄,reader。
  75.      */
  76.     public StreamTokenizer(Reader r) {
  77.         this();
  78.         if (r == null) {
  79.             throw new NullPointerException();
  80.         }
  81.         reader = r;
  82.     }
  83.     /**
  84.      * 该方法用于重置标记的语法表,通过一个循环,将语法表中的每一个元素都置为0,即当做普通字符进行处理。
  85.      */
  86.     public void resetSyntax() {
  87.         for (int i = ctype.length; --i >= 0;)
  88.             ctype[i] = 0;
  89.     }
  90.     /**
  91.      * 用于初始化语法表,传入的两个参数,为语法表的前后区间,将传入区间内的数据
  92.      */
  93.     public void wordChars(int low, int hi) {
  94.         if (low < 0)
  95.             low = 0;
  96.         if (hi >= ctype.length)
  97.             hi = ctype.length - 1;
  98.         while (low <= hi)
  99.             ctype[low++] |= CT_ALPHA;
  100.     }
  101.     /**
  102.      * 用于初始化语法表,传入的两个参数,为语法表的前后区间,将传入区间内的数据都做为空白空格处理。
  103.      */
  104.     public void whitespaceChars(int low, int hi) {
  105.         if (low < 0)
  106.             low = 0;
  107.         if (hi >= ctype.length)
  108.             hi = ctype.length - 1;
  109.         while (low <= hi)
  110.             ctype[low++] = CT_WHITESPACE;
  111.     }
  112.     /**
  113.      * 用于初始化语法表,传入的两个参数,为语法表的前后区间,将传入区间内的数据都做为普通字符处理。
  114.      */
  115.     public void ordinaryChars(int low, int hi) {
  116.         if (low < 0)
  117.             low = 0;
  118.         if (hi >= ctype.length)
  119.             hi = ctype.length - 1;
  120.         while (low <= hi)
  121.             ctype[low++] = 0;
  122.     }
  123.     /**
  124.      * 用于初始化语法表,通过传入的参数作为语法表的索引,将对应的类型改为0,这样便会当做普通字符处理。
  125.      */
  126.     public void ordinaryChar(int ch) {
  127.         if (ch >= 0 && ch < ctype.length)
  128.             ctype[ch] = 0;
  129.     }
  130.     /**
  131.      * 用于初始化语法表,以传入的int型值为索引,将其对应的数组划分到CT_COMMENT注解类型。
  132.      */
  133.     public void commentChar(int ch) {
  134.         if (ch >= 0 && ch < ctype.length)
  135.             ctype[ch] = CT_COMMENT;
  136.     }
  137.     /**
  138.      * 用于初始化语法表,以传入的int型值为索引,将其对应的数组划分到CT_QUOTE引用类型。
  139.      */
  140.     public void quoteChar(int ch) {
  141.         if (ch >= 0 && ch < ctype.length)
  142.             ctype[ch] = CT_QUOTE;
  143.     }
  144.     /**
  145.      * 用于初始化语法表,将数字0-9,'.','-'划分到CT_DIGIT数字类型。
  146.      */
  147.     public void parseNumbers() {
  148.         for (int i = '0'; i <= '9'; i++)
  149.             ctype[i] |= CT_DIGIT;
  150.         ctype['.'] |= CT_DIGIT;
  151.         ctype['-'] |= CT_DIGIT;
  152.     }
  153.     /**
  154.      * 该方法用于设置eolIsSignificant变量的值,该值用来恒定是否将行的结尾当做一个标记来处理。
  155.      */
  156.     public void eolIsSignificant(boolean flag) {
  157.         eolIsSignificantP = flag;
  158.     }
  159.     /**
  160.      * 该方法用于设置slashStarCommnetsP的值,该值用于恒定是否将c语言形式的注释当做特殊字符处理,如果为true,则所有包含在注释内的内容会被丢弃。为false,则
  161.      * 当做普通字符处理。
  162.      */
  163.     public void slashStarComments(boolean flag) {
  164.         slashStarCommentsP = flag;
  165.     }
  166.     /**
  167.      * 该方法与上一个方法类似,不过是用来恒定是否认可c++形式的注释。
  168.      */
  169.     public void slashSlashComments(boolean flag) {
  170.         slashSlashCommentsP = flag;
  171.     }
  172.     /**
  173.      * 该方法用于修改forceLower变量的值。
  174.      */
  175.     public void lowerCaseMode(boolean fl) {
  176.         forceLower = fl;
  177.     }
  178.     /**
  179.      * 定义了一个read函数,实际上是通过调用内置的reader/input 的read函数,从中看出,优先是使用reader来进去读取的。
  180.      */
  181.     private int read() throws IOException {
  182.         if (reader != null)
  183.             return reader.read();
  184.         else if (input != null)
  185.             return input.read();
  186.         else
  187.             throw new IllegalStateException();
  188.     }
  189.     /**
  190.      * 该函数用于获取下一个标记。
  191.      */
  192.     public int nextToken() throws IOException {
  193.         //判断是否需要进行回退,如果pushedBack值为true,则直接返回上一个标记的类型,同时将pushedBack的值重置为false。
  194.         if (pushedBack) {
  195.             pushedBack = false;
  196.             return ttype;
  197.         }
  198.         byte ct[] = ctype;
  199.         sval = null;
  200.         int c = peekc;
  201.         if (c < 0)
  202.             c = NEED_CHAR;
  203.         if (c == SKIP_LF) {
  204.             c = read();
  205.             if (c < 0)
  206.                 return ttype = TT_EOF;
  207.             if (c == '\n')
  208.                 c = NEED_CHAR;
  209.         }
  210.         if (c == NEED_CHAR) {
  211.             c = read();
  212.             if (c < 0)
  213.                 return ttype = TT_EOF;
  214.         }
  215.         ttype = c;              /* Just to be safe */
  216.         peekc = NEED_CHAR;//将peekc重置,方便下一次进入方法时使用  
  217.         //如果当前类型是空格,进行的操作
  218.         int ctype = c < 256 ? ct[c] : CT_ALPHA;
  219.         while ((ctype & CT_WHITESPACE) != 0) {
  220.             if (c == '\r') {
  221.                 LINENO++;
  222.                 if (eolIsSignificantP) {
  223.                     peekc = SKIP_LF;
  224.                     return ttype = TT_EOL;
  225.                 }
  226.                 c = read();
  227.                 if (c == '\n')
  228.                     c = read();
  229.             } else {
  230.                 if (c == '\n') {
  231.                     LINENO++;
  232.                     if (eolIsSignificantP) {
  233.                         return ttype = TT_EOL;
  234.                     }
  235.                 }
  236.                 c = read();
  237.             }
  238.             if (c < 0)
  239.                 return ttype = TT_EOF;
  240.             ctype = c < 256 ? ct[c] : CT_ALPHA;
  241.         }
  242.         //如果当前类型为数字的操作
  243.         if ((ctype & CT_DIGIT) != 0) {
  244.             boolean neg = false;
  245.             if (c == '-') {
  246.                 c = read();
  247.                 if (c != '.' && (c < '0' || c > '9')) {
  248.                     peekc = c;
  249.                     return ttype = '-';
  250.                 }
  251.                 neg = true;
  252.             }
  253.             double v = 0;
  254.             int decexp = 0;
  255.             int seendot = 0;
  256.             while (true) {
  257.                 if (c == '.' && seendot == 0)
  258.                     seendot = 1;
  259.                 else if ('0' <= c && c <= '9') {
  260.                     v = v * 10 + (c - '0');
  261.                     decexp += seendot;
  262.                 } else
  263.                     break;
  264.                 c = read();
  265.             }
  266.             peekc = c;
  267.             if (decexp != 0) {
  268.                 double denom = 10;
  269.                 decexp--;
  270.                 while (decexp > 0) {
  271.                     denom *= 10;
  272.                     decexp--;
  273.                 }
  274.                 /* Do one division of a likely-to-be-more-accurate number */
  275.                 v = v / denom;
  276.             }
  277.             nval = neg ? -v : v;
  278.             return ttype = TT_NUMBER;
  279.         }
  280.         //如果当前类型为字母符号的操作
  281.         if ((ctype & CT_ALPHA) != 0) {
  282.             int i = 0;
  283.             do {
  284.                 if (i >= buf.length) {
  285.                     buf = Arrays.copyOf(buf, buf.length * 2);//自动扩容
  286.                 }
  287.                 buf[i++] = (char) c;
  288.                 c = read();
  289.                 ctype = c < 0 ? CT_WHITESPACE : c < 256 ? ct[c] : CT_ALPHA;
  290.             } while ((ctype & (CT_ALPHA | CT_DIGIT)) != 0);
  291.             peekc = c;
  292.             sval = String.copyValueOf(buf, 0, i);
  293.             if (forceLower)
  294.                 sval = sval.toLowerCase();
  295.             return ttype = TT_WORD;
  296.         }
  297.         //如果当前类型为引用符号的操作
  298.         if ((ctype & CT_QUOTE) != 0) {
  299.             ttype = c;
  300.             int i = 0;
  301.             /* Invariants (because \Octal needs a lookahead):
  302.              *   (i)  c contains char value
  303.              *   (ii) d contains the lookahead
  304.              */
  305.             int d = read();
  306.             while (d >= 0 && d != ttype && d != '\n' && d != '\r') {
  307.                 if (d == '\\') {
  308.                     c = read();
  309.                     int first = c;   /* To allow \377, but not \477 */
  310.                     if (c >= '0' && c <= '7') {
  311.                         c = c - '0';
  312.                         int c2 = read();
  313.                         if ('0' <= c2 && c2 <= '7') {
  314.                             c = (c << 3) + (c2 - '0');
  315.                             c2 = read();
  316.                             if ('0' <= c2 && c2 <= '7' && first <= '3') {
  317.                                 c = (c << 3) + (c2 - '0');
  318.                                 d = read();
  319.                             } else
  320.                                 d = c2;
  321.                         } else
  322.                           d = c2;
  323.                     } else {
  324.                         c = switch (c) {
  325.                             case 'a' -> 0x7;
  326.                             case 'b' -> '\b';
  327.                             case 'f' -> 0xC;
  328.                             case 'n' -> '\n';
  329.                             case 'r' -> '\r';
  330.                             case 't' -> '\t';
  331.                             case 'v' -> 0xB;
  332.                             default  -> c;
  333.                         };
  334.                         d = read();
  335.                     }
  336.                 } else {
  337.                     c = d;
  338.                     d = read();
  339.                 }
  340.                 if (i >= buf.length) {
  341.                     buf = Arrays.copyOf(buf, buf.length * 2);
  342.                 }
  343.                 buf[i++] = (char)c;
  344.             }
  345.             peekc = (d == ttype) ? NEED_CHAR : d;
  346.             sval = String.copyValueOf(buf, 0, i);
  347.             return ttype;
  348.         }
  349.         //对待注解形式的处理。
  350.         if (c == '/' && (slashSlashCommentsP || slashStarCommentsP)) {
  351.             c = read();
  352.             if (c == '*' && slashStarCommentsP) {
  353.                 int prevc = 0;
  354.                 while ((c = read()) != '/' || prevc != '*') {
  355.                     if (c == '\r') {
  356.                         LINENO++;
  357.                         c = read();
  358.                         if (c == '\n') {
  359.                             c = read();
  360.                         }
  361.                     } else {
  362.                         if (c == '\n') {
  363.                             LINENO++;
  364.                             c = read();
  365.                         }
  366.                     }
  367.                     if (c < 0)
  368.                         return ttype = TT_EOF;
  369.                     prevc = c;
  370.                 }
  371.                 return nextToken();
  372.             } else if (c == '/' && slashSlashCommentsP) {
  373.                 while ((c = read()) != '\n' && c != '\r' && c >= 0);
  374.                 peekc = c;
  375.                 return nextToken();
  376.             } else {
  377.                 /* Now see if it is still a single line comment */
  378.                 if ((ct['/'] & CT_COMMENT) != 0) {
  379.                     while ((c = read()) != '\n' && c != '\r' && c >= 0);
  380.                     peekc = c;
  381.                     return nextToken();
  382.                 } else {
  383.                     peekc = c;
  384.                     return ttype = '/';
  385.                 }
  386.             }
  387.         }
  388.         //对于当前类型是注解时的操作。
  389.         if ((ctype & CT_COMMENT) != 0) {
  390.             while ((c = read()) != '\n' && c != '\r' && c >= 0);
  391.             peekc = c;
  392.             return nextToken();
  393.         }
  394.         return ttype = c;
  395.     }
  396.      /**
  397.      * 调用该函数时,首先进行安全检测,如果ttype不为TT_NOTHING,即已经调用过nextToken函数,那么将pushedBack的值设为true,下一次执行nextToeken函数时,
  398.      * 便不会修改当前标记的类型,同时也不会去修改当前nval或者sval的值。
  399.      */
  400.     public void pushBack() {
  401.         if (ttype != TT_NOTHING)   /* No-op if nextToken() not called */
  402.             pushedBack = true;
  403.     }
  404.     /**
  405.      * 该函数返回LINENO的值,即分割标记后最后的行数,值得注意的是如果将换行符设置为普通字符的话,会影响该函数的准确性。
  406.      */
  407.     public int lineno() {
  408.         return LINENO;
  409.     }
  410.     /**
  411.      * 该函数可以得到一个字符串,字符串内容为当前标记的类型,以及标记所在的行数。
  412.      */
  413.     public String toString() {
  414.         String ret = switch (ttype) {
  415.             case TT_EOF     -> "EOF";
  416.             case TT_EOL     -> "EOL";
  417.             case TT_WORD    -> sval;
  418.             case TT_NUMBER  -> "n=" + nval;
  419.             case TT_NOTHING -> "NOTHING";
  420.             default         -> {
  421.                 if (ttype < 256 && ((ctype[ttype] & CT_QUOTE) != 0)) {
  422.                     yield sval;
  423.                 }
  424.                 char s[] = new char[3];
  425.                 s[0] = s[2] = '\'';
  426.                 s[1] = (char) ttype;
  427.                 yield new String(s);
  428.             }
  429.         };
  430.         return "Token[" + ret + "], line " + LINENO;
  431.     }
  432. }
复制代码
2.1、StreamTokenize的2种利用方法

2.1.1、剖析空格、"(英文单引号)、/(反斜杠)

  我的windows操纵体系的D盘下有一个StreamTokenizer.txt文件,该文件的内容如下所示:

可以利用FileReader读取这个文件,然后利用StreamTokenizer来读取该文件中的每一个token以及该token对应的行号
  1. import java.io.*;
  2. public class StreamTokenizerTest {
  3.     public static void main(String[] args) throws UnsupportedEncodingException,
  4.             FileNotFoundException {
  5.         //通过传入一个FileReader来构建一个StreamTokenizer。这里读取的是本地的一个txt文件。
  6.         StreamTokenizer stk = new StreamTokenizer(new FileReader(new File(
  7.                 "D:\\StreamTokenizer.txt")));
  8.         try {
  9.             //当没有读取到文件结尾时,不停调用nextToken方法,然后将每一个token及其行号打印出来。
  10.             while (stk.nextToken() != StreamTokenizer.TT_EOF) {
  11.                 String s = null;
  12.                 switch (stk.ttype) {
  13.                     case StreamTokenizer.TT_WORD:
  14.                         s = stk.sval;
  15.                         break;
  16.                     case StreamTokenizer.TT_NUMBER:
  17.                         s = String.valueOf(stk.nval);
  18.                         break;
  19.                     default:
  20.                         s = stk.sval;
  21.                 }
  22.                 System.out.println(stk.toString());
  23.             }
  24.         } catch (IOException e) {
  25.             e.printStackTrace();
  26.         }
  27.     }
  28. }
复制代码
上述代码的实验效果如下所示:

从效果中可以看出,通过nextToken()函数读取的数字型数据都是double范例的,假如不符合要求,需自行举行转换。StreamTokenizer会把双引号""中的内容作为一个Token处置惩罚,将//之后的内容作为解释(解释不会作为token举行读取),好比,修改上文中D盘下的StreamTokenizer.txt文件,如下所示:

再次实验上文中的StreamTokenizerTest.class,效果如下所示:

假如想让这些符号被当做平常符号来举行处置惩罚,只需调用StreamTokenize.class:rdinaryChar()函数即可将特别的字符也当做平常字符处置惩罚,好比修改上文中的StreamTokenizerTest.class,修改后如下所示:
  1. import java.io.*;
  2. public class StreamTokenizerTest {
  3.     public static void main(String[] args) throws UnsupportedEncodingException,
  4.             FileNotFoundException {
  5.         //通过传入一个FileReader来构建一个StreamTokenizer。这里读取的是本地的一个txt文件。
  6.         StreamTokenizer stk = new StreamTokenizer(new FileReader(new File(
  7.                 "D:\\StreamTokenizer.txt")));
  8.         stk.ordinaryChar('"');\\ \表示转义
  9.         stk.ordinaryChar('/');\\ /不用进行转义
  10.         try {
  11.             //当没有读取到文件结尾时,不停调用nextToken方法,然后将每一个token及其行号打印出来。
  12.             while (stk.nextToken() != StreamTokenizer.TT_EOF) {
  13.                 String s = null;
  14.                 switch (stk.ttype) {
  15.                     case StreamTokenizer.TT_WORD:
  16.                         s = stk.sval;
  17.                         break;
  18.                     case StreamTokenizer.TT_NUMBER:
  19.                         s = String.valueOf(stk.nval);
  20.                         break;
  21.                     default:
  22.                         s = stk.sval;
  23.                 }
  24.                 System.out.println(stk.toString());
  25.             }
  26.         } catch (IOException e) {
  27.             e.printStackTrace();
  28.         }
  29.     }
  30. }
复制代码
继续读取D盘下的StreamTokenizer.txt文件,该文件的内容如下所示:

上述代码的实验效果如下所示:

也可以利用StreamTokenize.class::resetSyntax()函数将每一个ASCII码表现的字符和中笔墨符串作为1个token举行处置惩罚,好比修改上文中的StreamTokenizerTest.class,修改后如下所示:
  1. import java.io.*;
  2. public class StreamTokenizerTest {
  3.     public static void main(String[] args) throws UnsupportedEncodingException,
  4.             FileNotFoundException {
  5.         //通过传入一个FileReader来构建一个StreamTokenizer。这里读取的是本地的一个txt文件。
  6.         StreamTokenizer stk = new StreamTokenizer(new FileReader(new File(
  7.                 "D:\\StreamTokenizer.txt")));
  8.         stk.resetSyntax();
  9.         try {
  10.             //当没有读取到文件结尾时,不停调用nextToken方法,然后将每一个token及其行号打印出来。
  11.             while (stk.nextToken() != StreamTokenizer.TT_EOF) {
  12.                 String s = null;
  13.                 switch (stk.ttype) {
  14.                     case StreamTokenizer.TT_WORD:
  15.                         s = stk.sval;
  16.                         break;
  17.                     case StreamTokenizer.TT_NUMBER:
  18.                         s = String.valueOf(stk.nval);
  19.                         break;
  20.                     default:
  21.                         s = stk.sval;
  22.                 }
  23.                 System.out.println(stk.toString());
  24.             }
  25.         } catch (IOException e) {
  26.             e.printStackTrace();
  27.         }
  28.     }
  29. }
复制代码
继续读取D盘下的StreamTokenizer.txt文件,该文件的内容如下所示:

上述代码的实验效果如下所示:

2.1.2、代替Scanner.class来读取下令行,并对下令行输入的内容举行token转换

  代码如下所示:
  1. import java.io.*;
  2. public class StreamTokenizerTest {
  3.     public static void main(String[] args) throws IOException {
  4.         //将标准输入流传入StreamTokenizer中。
  5.         StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
  6.         PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
  7.         int a, b;
  8.         while (in.nextToken() != StreamTokenizer.TT_EOF) {
  9.             a = (int) in.nval;
  10.             in.nextToken();
  11.             b = (int) in.nval;
  12.             //out.println(a + b);
  13.             System.out.println("a + b = " + (a + b));
  14.         }
  15.         //将缓存区中的数据真实写出。
  16.         out.flush();
  17.     }
  18. }
复制代码
上述代码的实验效果如下所示:

参考资料:
https://www.cnblogs.com/moonfish1994/p/10222414.html
https://www.kancloud.cn/sunxiaoshufu/java/385495
https://www.oschina.net/uploads/doc/javase-6-doc-api-zh_CN/java/io/StreamTokenizer.html

免责声明:如果侵犯了您的权益,请联系站长及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金.

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表