从阅读器中删除或忽略字符

bom*_*bac 5 java

我正在将所有角色都读成流.我正在使用inputStream.read读取它.这是java.io.Reader inputStream.在读入缓冲区时,如何忽略像@这样的特殊字符.

private final void FillBuff() throws java.io.IOException
  {
     int i;
     if (maxNextCharInd == 4096)
        maxNextCharInd = nextCharInd = 0;

     try {
        if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
                                            4096 - maxNextCharInd)) == -1)
        {
           inputStream.close();
           throw new java.io.IOException();
        }
        else
           maxNextCharInd += i;
        return;
     }
     catch(java.io.IOException e) {
        if (bufpos != 0)
        {
           --bufpos;
           backup(0);
        }
        else
        {
           bufline[bufpos] = line;
           bufcolumn[bufpos] = column;
        }
        throw e;
     }
  }
Run Code Online (Sandbox Code Playgroud)

Col*_*ert 8

您可以使用自定义FilterReader.

class YourFilterReader extends FilterReader{
    @Override
    public int read() throws IOException{
        int read;
        do{
            read = super.read();
        } while(read == '@');

        return read; 
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException{
        int read = super.read(cbuf, off, len);

        if (read == -1) {
            return -1;
        }

        int pos = off - 1;
        for (int readPos = off; readPos < off + read; readPos++) {
            if (read == '@') {
                continue;
            } else {
                pos++;
            }

            if (pos < readPos) {
                cbuf[pos] = cbuf[readPos];
            }
        }
        return pos - off + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

资源:

在同一主题上:

  • 我认为循环中的第一行应该是`if(cbuf [readPos] =='@'){`.现在正在测试的`read`变量对于循环的每次迭代都保持不变. (2认同)

And*_*s_D 5

所有这些读取器,编写器和流都实现装饰器模式。每个装饰器都会向基础实现添加其他行为和功能。

一个满足您要求的解决方案可以是FilterReader:

public class FilterReader implements Readable, Closeable {
  private Set<Character> blacklist = new HashSet<Character>();
  private Reader reader;      

  public FilterReader(Reader reader) {
    this.reader = reader;
  }

  public void addFilter(char filtered) {
    blacklist.add(filtered);
  }

  @Override
  public void close() throws IOException {reader.close();}

  @Override
  public int read(char[] charBuf) {
    char[] temp = new char[charBuf.length];
    int charsRead = reader.read(temp);
    int index = -1;
    if (!(charsRead == -1)) {
      for (char c:temp) {
        if (!blacklist.contains(c)) {
          charBuf[index] = c;
          index++;
         }
      }
    }
    return index;
  }

}
Run Code Online (Sandbox Code Playgroud)

注意-该类java.io.FilterReader是具有零功能的装饰器。您可以扩展它,也可以忽略它并创建自己的装饰器(在这种情况下,我更喜欢)。


Mar*_*lze 0

您可以实现从 InputStream 派生的自己的输入流。然后重写读取方法,以便它们从流中过滤出特殊字符。