为什么在使用来自 apcache.commons 的 CSVPrinter 时,close() 方法在 Intellij 中突出显示为冗余?
Why is close() method highlighted as redundant in Intellij, when using CSVPrinter from apcache.commons?
我正在使用 apache.commons.csv 中的 CSVPrinter class,我正在尝试打印 csv 文件中的一些行。据我所知,在写入完成后,我们需要在 FileWriter
上调用 close()
方法。基于该假设,我尝试调用 CSVPrinter.close()
。但是,IntelliJ IDEA 警告我此方法是多余的。此外,https://www.callicoder.com/java-read-write-csv-file-apache-commons-csv/中的示例也不包含此方法。我想知道为什么那个方法是多余的,如果我只使用 .flush() 一切都会好起来的?
这是从上述网站复制的示例。
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class CSVWriter {
private static final String SAMPLE_CSV_FILE = "./sample.csv";
public static void main(String[] args) throws IOException {
try (
BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
.withHeader("ID", "Name", "Designation", "Company"));
) {
csvPrinter.printRecord("1", "Sundar Pichai ♥", "CEO", "Google");
csvPrinter.printRecord("2", "Satya Nadella", "CEO", "Microsoft");
csvPrinter.printRecord("3", "Tim cook", "CEO", "Apple");
csvPrinter.printRecord(Arrays.asList("4", "Mark Zuckerberg", "CEO", "Facebook"));
csvPrinter.flush();
// I added the following line
csvPrinter.close();
}
}
}
正如@user207421 在评论中解释的那样。
首先: try-with-resources 语句在其范围结束时提供自动关闭。
其次:关闭前Flush是多余的
我正在使用 apache.commons.csv 中的 CSVPrinter class,我正在尝试打印 csv 文件中的一些行。据我所知,在写入完成后,我们需要在 FileWriter
上调用 close()
方法。基于该假设,我尝试调用 CSVPrinter.close()
。但是,IntelliJ IDEA 警告我此方法是多余的。此外,https://www.callicoder.com/java-read-write-csv-file-apache-commons-csv/中的示例也不包含此方法。我想知道为什么那个方法是多余的,如果我只使用 .flush() 一切都会好起来的?
这是从上述网站复制的示例。
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class CSVWriter {
private static final String SAMPLE_CSV_FILE = "./sample.csv";
public static void main(String[] args) throws IOException {
try (
BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
.withHeader("ID", "Name", "Designation", "Company"));
) {
csvPrinter.printRecord("1", "Sundar Pichai ♥", "CEO", "Google");
csvPrinter.printRecord("2", "Satya Nadella", "CEO", "Microsoft");
csvPrinter.printRecord("3", "Tim cook", "CEO", "Apple");
csvPrinter.printRecord(Arrays.asList("4", "Mark Zuckerberg", "CEO", "Facebook"));
csvPrinter.flush();
// I added the following line
csvPrinter.close();
}
}
}
正如@user207421 在评论中解释的那样。
首先: try-with-resources 语句在其范围结束时提供自动关闭。
其次:关闭前Flush是多余的