Replace line segment from input stream

I am trying to get a huge text file as input stream and want to convert a line segment with another line. I am very confused how to do this, it works well if I convert the entire input stream into a string that I do not want, as part of the content is lost. can anyone help how to do this? for example, if I have a file with the content "This is a test string that needs to be changed." I want to accept this line as an input stream and I want to change the contents to "This is the test line that was changed" (by replacing "need 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 result to be as follows: This is a test string that has been modified

Thank you in advance.

+6
source share
2 answers

If the text you want to change will always be on the same logical line, as I said in the comment, I would go with a simple read of the line (if applicable), 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 always liked to use inheritance, so I would define it 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 instead of the standard BufferedReader, keeping the substitution hidden inside the readLine method.

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

NTN

+4
source

Maybe I realized that you are mistaken, but I think you should create a stack computer. I mean, you can use a small stack to collect text and check for replacement conditions.

Unless the stacked stack already matches your state, simply clear the stack for output and pick it up again.

If your stack is similar to the condition, continue collecting it.

If your stack meets your condition, make a modification and clear the modified stack for output.

+2
source

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


All Articles