replace a string segment from input stream

inputstream, java

Solution

If the text to be changed will always fit in one logical line, as I stated in comment, I'd go with simple Line Reading (if applyable) using something like:

public class InputReader {
    public static void main(String[] args) throws IOException
    {
        String string = "This is the test string which needs to be modified";
        InputStream inpstr = new ByteArrayInputStream(string.getBytes());

        BufferedReader rdr = new BufferedReader(new InputStreamReader(inpstr));
        String buf = null;
        while ((buf = rdr.readLine()) != null) {
            // Apply regex on buf

            // build output
        }
    }
}

However I've always like to use inheritance so I'd define this somewhere:

class MyReader extends BufferedReader {
    public MyReader(Reader in)
    {
        super(in);
    }

    @Override
    public String readLine() throws IOException {
        String lBuf = super.readLine();
        // Perform matching & subst on read string
        return lBuf;
    }
}

And use MyReader in place of standard BufferedReader keeping the substitution hidden inside the readLine method.

Pros: substitution logic is in a specified Reader, code is pretty standard. Cons: it hides the substitution logic to the caller (sometimes this is also a pro, still it depends on usage case)

HTH

Problem

I am trying to receive a huge text file as an inputstream and want to convert a string segment with another string. I am strictly confused how to do it, it works well if I convert whole inputstream as a string which I don't want as some of the contents are lost. can anyone please help how to do it?? e.g. if I have a file which has the contents "This is the test string which needs to be modified". I want to accept this string as input stream and want to modify the contents to "This is the test string which is modified" , ( by replacing 'needs to be' with is). ``` public static void main(String[] args) { String string = "This is the test string which needs to be modified"; InputStream inpstr = new ByteArrayInputStream(string.getBytes()); //Code to do } ``` In this I want the output as: This is the test string which is modified Thanking you in advance.

Original source