简体   繁体   中英

Log using BufferedReader and ScheduledExecutor

I'm currently studying for my JAVA SE OCP Certification so and playing around with things to learn.

I'm currently on IO chapter. I'm trying to combine a ScheduledExecutor with a BufferedWriter

ScheduledExecutorService service = null;
try (BufferedWriter bw = new BufferedWriter(new FileWriter(testFile))) {
    service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        try {
            bw.write("Curr Time: " + LocalTime.now());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }, 1, 1, TimeUnit.SECONDS);
}

I expected to write the LocalTime every second on a new line on my TestFile but this IOException shows up:

java.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:116)
at java.io.BufferedWriter.write(BufferedWriter.java:221)
at java.io.Writer.write(Writer.java:157)
at Worksheet.lambda$main$0(Worksheet.java:56)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) {...}

Try with:

ScheduledExecutorService service = null;
    service = Executors.newSingleThreadScheduledExecutor();
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(testFile, true));
        service.scheduleAtFixedRate(() -> {
            try {
                bw.write("Curr Time: " + LocalTime.now() + "\n");
                bw.flush();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS);

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

The true parameter in the FileWriter will append each new line to the existing file, instead of creating a new file.

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