【问题标题】:Best way to check if file exist and it is readable in java [closed]检查文件是否存在并且在java中可读的最佳方法[关闭]
【发布时间】: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.
}

【问题讨论】:

  • 您的第一个选项检查您实际执行的操作,而您的第二个选项首先执行一些检查,稍后再执行一些操作,这会为竞争条件打开一个窗口。这在现实中更经常发生,例如当两个日常工作同时运行时。但实际上,这主要是一个意见问题,我会投票结束。

标签: java file java-io


【解决方案1】:

我会搬到java.nio 完全,这意味着完全摆脱java.io,然后选择您的第二个选项的略微调整版本:

public static void main(String[] args) {
    Path file = Paths.get("L:\\ocation\\of\\the\\file");
    if (!Files.exists(file)) {
        // File does not exist
    } else if (!Files.isRegularFile(file)) {
        // File is not a file, maybe a directory
    } else if (!Files.isReadable(file)) {
        // File is not readable.
    } else {
        // everything is right, process the file
    }
}

这个问题可能是基于某种观点,但我认为这主要不是由于旧包和现代包的比较。

【讨论】:

  • isRegularFile()"[follows] 符号链接 [...] 并且读取链接的最终目标的文件属性"。
  • 这是正确答案。 java.io.File 是旧的,应该避免使用它,除非它是绝对必要的(例如在使用其他需要 int 的 API 时)。
  • @Andreas 谢谢,我从代码注释中删除了相关字词
  • 如果可以避免,不要嵌套if 语句,即恢复外部if 语句的条件,就像已经为第一个内部if 语句所做的那样。然后在随后的if 语句中将if 更改为else if,因为不能保证if 块不会正常完成。总之,代码应该是if (! exists) { ... } else if (! isRegularFile) { ... } else if (! isReadable) { ... } else { ... use file here ... }
  • @Andreas 是的,再次感谢。我稍后会更新这个,现在,这只是一个快速的答案......
猜你喜欢
  • 2010-11-25
  • 2017-02-22
  • 2010-09-18
  • 1970-01-01
  • 2010-12-20
相关资源
最近更新 更多