Updating text file using java

时间:2016-11-26 18:31:46

标签: java io filewriter

I am doing an assignment and part of it I need to loop through a text file and output information depending on certain search terms which I have done, but after that I need to edit the document on one of the lines that the user would accept, my code to edit the document is:

int y = null;
PrintWriter write = new PrintWriter(fileName);
if (confirmation.equals("Y")) {
                    System.out.println("What is your email to confirm your booking?");
                    email = S.next();

                    write.println(room + (" ") + roomB + (" ") + price + (" ") + pool + (" ") + lounge + (" ") + email);
                    y = 1;
                }

What happens after it finishes it will write just the one line and delete the rest of the data instead of just changing that one line.

1 个答案:

答案 0 :(得分:2)

我认为你的问题是println()并不关心文件中的内容。它只是写入流,导致覆盖现有内容。

如果您只需更改一行,请考虑读取现有文件内容,然后替换该内容中的行,然后将整个修改后的内容写入文件。

当然,您必须记住,如果文件很大,一次阅读整个内容可能会变得昂贵或危险,因此可能需要进行一些优化。