Replace characters with Java 1.4 InputStream

I have an InputStream that is returned, for example:

<?xml version='1.0' ?><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"><bbs:rule xmlns:bbs="http://com.foo/bbs">

Then I pass the stream to a method that returns an array of bytes. I would like to replace "com.foo" with something else, such as "org.bar", before moving on to the byte [] method.

What is a good way to do this?

+3
source share
4 answers

If you have a bytearray, you can convert it to a string. Pay attention to the encoding, in the example I use utf-8. I think this is an easy way to do this:

String newString = new String(byteArray, "utf-8");
newString = newString.replace("com.foo", "org.bar");
return newString.getBytes("utf-8");
+1
source

, InputStream FilterInputStream, " ". , "c", , "om.foo", , . , read().

+1

/ . . , , , Reader (, InputStreamReader), . , , . , UTF-8 ISO-8859-1.

, , , . - . , , . .

XML-, XML , , . SAXParser ContentHandler . , . XSLT .

Wasn't there some kind of support for manipulating threads like this in java.nio? Or was it planned for a future version of Java?

+1
source

This may not be the most efficient way to do this, but it certainly works.

    InputStream is = // input;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));

    String line = null;

    while((line = reader.readLine()) != null)
    {
        if(line.contains("com.foo"))
        {
            line = line.replace("com.foo", "org.bar");
        }

        writer.write(line);
    }

    return baos.toByteArray();
0
source

Source: https://habr.com/ru/post/1796382/


All Articles