Good day, I have such a problem. It is necessary to add text to the file, but from a new line. And it’s not easy to add, but what would the program request from the user when adding it? First: Title :, then Year :, and then Author’s name :. I use this method to write to the file, but it simply adds to the existing line.

if (sc==6){ System.out.println("Введите новую книгу:"); String filePath = "Lib.txt"; Scanner console = new Scanner(System.in); try {FileWriter out = new FileWriter(filePath, true); BufferedWriter bufferWriter = new BufferedWriter(out); bufferWriter.write(console.next()); bufferWriter.close(); } catch (IOException e) { System.err.println(e); } } 

    1 answer 1

    Naturally, it will add to the existing line if there is no line feed at the end. There is no universal way here. If, as in your case, there is no line feed in the last line of the file, then

     bufferWriter.write(console.next()); 

    add

     bufferWriter.newLine(); 

    If there is a newline, then this method will create an extra empty string.

    If you know for sure that there will always be no line newLine() at the end of the last line - add newLine() .