Change InputStream by applying regex on it

∥☆過路亽.° 提交于 2020-03-06 05:14:51

问题


I have an InputStream downloaded from the internet. And I need to apply regex on it - so that all occurrences of that regex would be changed to string, wich is provided. I need an InputStream as a return value since it should be forwarded to api.

Basically, such signature would be the best:

InputStream applyRegex(InputStream stream, Pattern pattern, String changeString){
    ...
}

I have very basic knowledge of working with streams, please give an answer in method form, if it is possible.

By the way, input stream I receive has size 0, until I call method read(byte[])


回答1:


Managed to get it working with github.com/rwitzel/streamflyer library. if app.gradle we have:

compile 'com.github.rwitzel.streamflyer:streamflyer-core:1.2.0';

Example:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;

import com.github.rwitzel.streamflyer.core.ModifyingReader;
import com.github.rwitzel.streamflyer.regex.RegexModifier;

public class InputStreamModifiedWithRegex {
    private static final Charset ENCODE_CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException {
        InputStream input = IOUtils.toInputStream("AB CD EF");
        InputStream updatedInput = applyRegex(input, "[A-C]", "Z");
        System.out.println(IOUtils.toString(updatedInput, ENCODE_CHARSET));
    }

    private static InputStream applyRegex(InputStream inputStream, String pattern, String changeString)
            throws UnsupportedEncodingException {
        Reader originalReader = new InputStreamReader(inputStream, ENCODE_CHARSET);
        Reader modifyingReader = new ModifyingReader(originalReader, new RegexModifier(pattern, 0, changeString));
        inputStream = new ReaderInputStream(modifyingReader, ENCODE_CHARSET);

        return inputStream;
    }
}


来源:https://stackoverflow.com/questions/45079436/change-inputstream-by-applying-regex-on-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!