简体   繁体   中英

I wonder why FileWiter.write and PrintWrite.println cannot be executed together in the code

        fw = new FileWriter(f);
        pw = new PrintWriter(f);
        while (true) {
            System.out.println("값을 입력하세요");
            String input = br.readLine();
            if (input.equals("exit")) {
                break;
            }
            fw.write(input + "\r\n");
            // \r 커서를 맨앞으로 이동시켜줌. 이젠 \n하면 자동으로 된다.
            pw.println(input);
            // PrintWrite의 경우 println을 써서 \r이나 \n등을 안써도 된다.
        }

I thought that the input value would be entered twice in the file, but I am curious as to why it is entered only once.

Once i guess, it seems that it is inputted only once because it is separately input to the pw object and the fw object.

is this right?

You typically can't open two writers to the same file at the same time. Either one will fail entirely or they will be saved in the order that they are written, it depends on how the buffer works and when the write takes place.

Add this to the end of your code:

fw.flush();
fw.close();
pw.flush();
pw.close();

If we do the above then pw will close last and that will be what you see in the file, however, if we do the below then fw will close last and be what you see in the file:

pw.flush();
pw.close();
fw.flush();
fw.close();

You can verify this by changing your code to add extra characters and seeing what happens when you close one before the other:

fw.write(input + " AA\r\n");
pw.println(input+" BB");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM