I would like to save text to a file such that certain paragraphs are indented (each line of the paragraph is indented). I’m using BufferedWriter or Scanner or whatever. How would I go about doing this without counting characters?
I would like to save text to a file such that certain paragraphs are
Share
You will have to find all newlines, and insert the appropriate number of spaces after each newline.
So, the code will always need to look at each character, and possibly also parsing the text in order find where and how much to indent.
You can implement your
java.io.Writerthat handles the parsing and formatting. Even though the most efficient way is to work directly on char buffers, it is also a lot more complicated than just creating a new String and use the String functions, so its usually best to go for stability before efficiency.If the indentation is the same for the whole file, you can do a simple String.replaceAll() and replace newlines with a newline followed by a number of spaces. If you need dynamic indentation, you probably need to parse (find) where the indentation level changes, check each character if its newline or indentation level change, buy now it’s getting complicated…