Search code examples
javafileprintwriter

Keeping line breaks when reading a file


I want to read a file and modify it but whenever the new file is created everything stays on one line. Therefore, my question is how can I keep line breaks without removing them?

public class JavaProgram {

    public static void main(String[] args) {
        String text = "";
        StringBuilder convert = new StringBuilder();
        Scanner keyboard = new Scanner (System.in);

        File file = new File ("PATH");

            try {
                Scanner input = new Scanner (file);
                while (input.hasNextLine()) {
                        text = input.nextLine();

                        char [] arr = text.toCharArray();
                        char [] newArr = encrypt(3, arr);

                        for (int i = 0; i < newArr.length; i++) {
                            convert.append(newArr[i]);
                } catch (IOException e) {
                    e.printStackTrace(); 
                }
                try {
                    PrintWriter printer = new PrintWriter (document);

                    printer.append(convert);
                    printer.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

Solution

  • Add the line break at the moment you write each line. In your case is after the for loop that appends the encrypted characters:

    for (int i = 0; i < newArr.length; i++) {
           convert.append(newArr[i]);
    convert.append("\r\n");
    

    Adding a new line in Java is as simple as including “\n” or “\r” or “\r\n” at the end of our string depending on the SO you are using. But nowadays the file editors recognise all of them so it might not be a problem whether you chose one or another.

    And regarding to why they are 'lost' if you look at the docs of the nextLine() method it says:

    Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

    So you have to add the line separators back if you need them.