Search code examples
javastringbuffer

How to split one line of text to multiple lines based on keyword/pattern?


I have a StringBuffer that contains what used to be multiple lines from a file, all merged together based on a pattern of larger lines for comparisons. After changes have been made, I basically need to undo merging the lines together to re-write to a new StringBuffer to re-write the file as it originally was.

So for example, the file contains a line like this (all on one line):

'macro NDD89 Start;Load; shortDescription; macro(continued) stepone;steptwo,do stuff macro(continued) stepthree;more steps; do stuff macro(continued) finalstep'

I need that line to be re-written to multiple lines (split wherever there is the string "macro(continued)"):

macro NDD89 Start;Load; shortDescription;
macro(continued) stepone;steptwo,do stuff
macro(continued) stepthree;more steps; do stuff
macro(continued) finalstep'

If it helps, here is my code snippet that does the first part of taking the original file where it is in multiple lines and combines them to groups and writes to a new file:

    StringBuffer sb = new StringBuffer();
    Buffer = new FileReader(C:/original.txt);
    BufferedReader User_File = new BufferedReader(Buffer);
    String Line_of_Text;
    while((Line_of_Text = User_File.readLine()) != null){
        if(Line_of_Text.startsWith("macro ")){
            sb.append("\n"+Line_of_Text);
        }else if(Line_of_Text.startsWith("macro(continued)")){
            sb.append(Line_of_Text);
        }else{
            sb.append(Line_of_Text+"\n");
        }
    }
    BufferedWriter OutFile = new BufferedWriter(new FileWriter("C:/newFile.txt"));
    OutFile.write(sb.toString());
    OutFile.flush();
    OutFile.close();

I have been stuck on a way to do this for a while, any suggestions/ideas?


Solution

  • The simplest solution!

    String x =oneLine.replace(" macro", "\nmacro");