How to split a string in java when there is a new line character?

52 Views Asked by At

I'm trying to write a large String that I have into a txt file, in said string there are a lot of \n and I'd like that to register as a new line in my txt file. I've tried to split the string whenever there is such a character in order to write it to the txt file as multiple lines but it didn't work. I've tried using String.replaceAll((\n),(\r\n)), but it did nothing. I've also tried String.split(\n), but again it did nothing. Am I doing something wrong? Is there another way of doing this?

recipes = recipes.replaceAll("(\n)", "(\r\n)");

I've also tried

try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
                    // *Split the string in lines
                    String[] lines = recipes.split("\n");
                    System.out.println("Split text into lines: " + lines.length);
                    for (String line : lines) {
                        bw.write(line);
                        bw.newLine(); // * Add a new line
                    }

                }

but I've had no luck.

Any help would be massively appreciated

0

There are 0 best solutions below