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

我正在将所有角色都读成流。 我正在使用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; } } 

您可以使用自定义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; } } 

资源:

  • Javadoc - FilterReader
  • BCRDF - 使用ReaderFilter跳过无效的XML字符

在同一主题上:

  • 从流中过滤/删除无效的xml字符

所有这些读者,作家和流都实现了Decorator模式。 每个装饰器都为底层实现添加了额外的行为和function。

您需要的解决方案可能是FilterReader:

 public class FilterReader implements Readable, Closeable { private Set blacklist = new HashSet(); 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; } } 

注意 – 类java.io.FilterReader是一个零function的装饰器。 您可以扩展它或只是忽略它并创建自己的装饰器(在这种情况下我更喜欢)。

您可以实现从InputStream派生的自己的输入流。 然后覆盖read方法,以便它们从流中过滤掉特殊字符。

 private final void FillBuff() throws java.io.IOException { int i; if (maxNextCharInd == 4096) maxNextCharInd = nextCharInd = 0; try { Reader filterReader = new FilterReader(inputStream) { public int read() { do { result = super.read(); } while (specialCharacter(result)); return result; } }; if ((i = filterReader.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; } }