栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在InputStream中过滤(搜索和替换)字节数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在InputStream中过滤(搜索和替换)字节数组

不确定您选择了解决问题的最佳方法。

就是说,我不喜欢(也有政策禁止)以“不”回答问题,所以这里…

看一看

FilterInputStream

从文档中:

FilterInputStream包含其他一些输入流,它用作其基本数据源, 可能会沿途转换数据 或提供其他功能。


编写它是一个有趣的练习。这是为您提供的完整示例:

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()));    }}

给定要

"Hello xyz world"
打印的字符串的字节数:

Hello abc world


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486386.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号