Filter (search and replace) array of bytes in an InputStream

后端 未结 6 1693
清歌不尽
清歌不尽 2020-11-30 05:49

I have an InputStream which takes the html file as input parameter. I have to get the bytes from the input stream .

I have a string: \"XYZ\". I\'d like

6条回答
  •  猫巷女王i
    2020-11-30 06:35

    I came up with this simple piece of code when I needed to serve a template file in a Servlet replacing a certain keyword by a value. It should be pretty fast and low on memory. Then using Piped Streams I guess you can use it for all sorts of things.

    /JC

    public static void replaceStream(InputStream in, OutputStream out, String search, String replace) throws IOException
    {
        replaceStream(new InputStreamReader(in), new OutputStreamWriter(out), search, replace);
    }
    
    public static void replaceStream(Reader in, Writer out, String search, String replace) throws IOException
    {
        char[] searchChars = search.toCharArray();
        int[] buffer = new int[searchChars.length];
    
        int x, r, si = 0, sm = searchChars.length;
        while ((r = in.read()) > 0) {
    
            if (searchChars[si] == r) {
                // The char matches our pattern
                buffer[si++] = r;
    
                if (si == sm) {
                    // We have reached a matching string
                    out.write(replace);
                    si = 0;
                }
            } else if (si > 0) {
                // No match and buffered char(s), empty buffer and pass the char forward
                for (x = 0; x < si; x++) {
                    out.write(buffer[x]);
                }
                si = 0;
                out.write(r);
            } else {
                // No match and nothing buffered, just pass the char forward
                out.write(r);
            }
        }
    
        // Empty buffer
        for (x = 0; x < si; x++) {
            out.write(buffer[x]);
        }
    }
    

提交回复
热议问题