Cashier.java 의 openFile()에 @PostConstruct 애너테이션, closeFile()에 @PreDestory 애너테이션 붙여줘야 에러가 나지 않습니다.
에러 내용
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.BufferedWriter.write(String)" because "this.writer" is null
at com.apress.spring6recipes.shop.Cashier.checkout(Cashier.java:34)
at com.apress.spring6recipes.shop.Main.main(Main.java:27)
Cashier.java
package com.apress.spring6recipes.shop;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
public class Cashier {
private final String fileName;
private final String path;
private BufferedWriter writer;
public Cashier(String fileName, String path) {
this.fileName = fileName;
this.path = path;
}
@PostConstruct
public void openFile() throws IOException {
var options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.APPEND };
var file = Path.of(path, fileName + ".txt");
Files.createDirectories(file.getParent());
writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8, options);
}
public void checkout(ShoppingCart cart) throws IOException {
writer.write(LocalDateTime.now() + "\t" + cart.getItems() + "\r\n");
writer.flush();
}
@PreDestroy
public void closeFile() throws IOException {
writer.close();
}
}
Cashier.java 의 openFile()에 @PostConstruct 애너테이션, closeFile()에 @PreDestory 애너테이션 붙여줘야 에러가 나지 않습니다.
에러 내용
Cashier.java