• Filter (seach and replace) array of bytes in an InputStream


    import java.io.*;
    import java.util.*;
    
    class ReplacingInputStream extends FilterInputStream {
    
        LinkedList<Integer> inQueue = new LinkedList<Integer>();
        LinkedList<Integer> outQueue = new LinkedList<Integer>();
        final byte[] search, replacement;
    
        protected ReplacingInputStream(InputStream in, byte[] search,
                                                       byte[] replacement) {
            super(in);
            this.search = search;
            this.replacement = replacement;
        }
    
        private boolean isMatchFound() {
            Iterator<Integer> inIter = inQueue.iterator();
            for (int i = 0; i < search.length; i++)
                if (!inIter.hasNext() || search[i] != inIter.next())
                    return false;
            return true;
        }
    
        private void readAhead() throws IOException {
            // Work up some look-ahead.
            while (inQueue.size() < search.length) {
                int next = super.read();
                inQueue.offer(next);
                if (next == -1)
                    break;
            }
        }
    
    
        @Override
        public int read() throws IOException {
    
            // Next byte already determined.
            if (outQueue.isEmpty()) {
    
                readAhead();
    
                if (isMatchFound()) {
                    for (int i = 0; i < search.length; i++)
                        inQueue.remove();
    
                    for (byte b : replacement)
                        outQueue.offer((int) b);
                } else
                    outQueue.add(inQueue.remove());
            }
    
            return outQueue.remove();
        }
    
        // TODO: Override the other read methods.
    }
    
    
    class Test {
        public static void main(String[] args) throws Exception {
    
            byte[] bytes = "hello xyz world.".getBytes("UTF-8");
    
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    
            byte[] search = "xyz".getBytes("UTF-8");
            byte[] replacement = "abc".getBytes("UTF-8");
    
            InputStream ris = new ReplacingInputStream(bis, search, replacement);
    
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
            int b;
            while (-1 != (b = ris.read()))
                bos.write(b);
    
            System.out.println(new String(bos.toByteArray()));
    
        }
    }
  • 相关阅读:
    在DNN模块开发中使用jQuery
    在MSBuild.exe中使用条件编译(Conditional Compile)
    ASP.NET SQL 注入免费解决方案
    html+css做圆角表格
    [ASP]sitemap地图生成代码
    刺穿MYIE|24小时同一ip弹一次|无须body加载|精简代码
    用ASPJPEG组件制作图片的缩略图和加水印
    16个经典面试问题回答思路[求职者必看]
    一个26岁IT男人写在辞职后
    搜弧IT频道的幻灯片切换的特效源代码
  • 原文地址:https://www.cnblogs.com/yqskj/p/3067464.html
Copyright © 2020-2023  润新知