Search code examples
javanio

Appending text to existing file without overwriting it


I'm adding some content into an existing file NameList.txt, which already contains some text there.

But when I run the program, it removes all the existing content before starting to write new ones.

Note: I also try to find where is the file ending line. E.g. by using while ((lines = reader.readLine()) == null), where the lines variable is of the type String.

public class AddBooks {

    public static void main(String[] args) {

        Path Source = Paths.get("NameList.txt");

        Charset charset = Charset.forName("Us-ASCII");
        try (
            BufferedWriter write = Files.newBufferedWriter(Source, charset);
            BufferedReader reader = Files.newBufferedReader(Source, charset);
        ) {
            Scanner input = new Scanner(System.in);
            String s;
            String line;
            int i = 0, isEndOfLine;

            do {
                System.out.println("Book Code");
                s = input.nextLine();
                write.append(s, 0, s.length());
                write.append("\t \t");

                System.out.println("Book Title");
                s = input.nextLine();
                write.append(s, 0, s.length());
                write.append("\t \t");

                System.out.println("Book Publisher");
                s = input.nextLine();
                write.append(s, 0, s.length());
                write.newLine();

                System.out.println("Enter more Books? y/n");
                s = input.nextLine();

            } while(s.equalsIgnoreCase("y"));
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

My only requirement is to add new content to existing file.


Solution

  • Change your code like this!

    BufferedWriter write = Files.newBufferedWriter(Source, charset, StandardOpenOption.APPEND);
    

    And see this! StandardOpenOption

    2nd..

     while ((str = in.readLine()) != null)
    

    Appendix.. insert

    writer.close();
    

    before

    } while(s.equalsIgnoreCase("y"));