0

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

2
  • You tried replaceAll("\\n", "\n") ? You need to do it for the OS you're on though, so recipes = recipes.replace("\\n", System.lineSeparator()); would be better Commented Dec 4, 2023 at 16:12
  • Yeah you are correct! I used that and then played around with some other things and I got it to work thanks! Commented Dec 4, 2023 at 16:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.