Search code examples
javastringrtffile-writing

Writing String to an rtf in java doesn't keep structure


I wrote a FileMerge class where I take an rtf and replace certain tags with SQL data. Everything is ok but one part in which I replace one tag with one or more lines, it replaces the file but \n or \r\n doesn't create a new line when opened in word.

the code:

String otherFamilyString="\n";


    for(int i=0;i<OtherFamily.size();i=i+TotalArguments)
    {
        otherFamilyString +=  "\n"+OtherFamily.get(i+FamilyMbrId) +"|\t"+ OtherFamily.get(i+FamilyMbrName) +"|\t"+ OtherFamily.get(i+FamilyStatus)+"|\t"
        + OtherFamily.get(i+FamilyCoveragetype) +"|  "+ OtherFamily.get(i+FamilyRelationship) +"|" ;
        System.out.print(i+" "+otherFamilyString);


    }
    newtext = newtext.replaceAll("OTHERFAMILY",otherFamilyString);



    FileWriter writer = new FileWriter(outPutDir+memberInfo.get(GroupId).replace(" ", "")+newName.replace("*", "")); 
    writer.write(newtext);//write the new file 
    writer.close();

I also tried System.getProperty("line.separator") unsuccessfully.

When I open the file in notepad, I can see that all of the code is in rich text except this part which shows in the right structure. I think I need a way to write this string in rich text format so it will show good in word.

Thank you for the help, Idan.


Solution

  • In RTF, line breaks are not indicated by a new line in the text - instead, you must use the right control sequence to do this. From skimming over the specification, \line looks like a hard line break, and \par like a paragraph break.