【发布时间】:2019-11-11 15:23:02
【问题描述】:
能否请您告诉我在 java 中检查文件是否存在和可读的最佳方法是什么?我想到了以下两种方式。但是,我想不出哪个更好。
选项#1-
String filePath = "file_location"
try (FileInputStream fis = new FileInputStream(filePath)) {
fis.read();
} catch (FileNotFoundException e) {
// File does not exist.
} catch (IOException e) {
// File is not readable.
}
选项#2-
import java.io.File;
import java.nio.file.Files;
File file = new File("file_location");
if (!Files.isRegularFile(file.toPath())) {
// File does not exist or it is not a file.
}
if (Files.isReadable(file.toPath())) {
// File is not readable.
}
【问题讨论】:
-
您的第一个选项检查您实际执行的操作,而您的第二个选项首先执行一些检查,稍后再执行一些操作,这会为竞争条件打开一个窗口。这在现实中更经常发生,例如当两个日常工作同时运行时。但实际上,这主要是一个意见问题,我会投票结束。