【问题标题】:Check if file already exist in the same path检查文件是否已存在于同一路径中
【发布时间】:2023-03-17 01:22:02
【问题描述】:

我想检查特定文件是否已存在于同一文件夹中。 如果它不存在,则创建一个新文件并输入某些内容。 例如。如果 filePath = test.txt 和 test.txt 不存在。 新建一个文件名test.txt,将12345放在文件的第一行。

目前,尽管满足条件,但我的方法甚至不会运行此 if 语句。 (test.txt 不存在)

    PrintWriter output;
    File file = new File(filePath);
    if(!file.isFile()){
        try {
            output = new PrintWriter(new FileWriter(filePath));
        } catch (IOException ex) {
            throw new PersistenceException("Error!", ex);
        }
        output.print("12345");
        output.flush();
        output.close();
    }

【问题讨论】:

  • 您可以将exists() 用于File 对象。
  • 如果它确实存在呢?如果它存在但没有 12345 怎么办?

标签: java file printwriter


【解决方案1】:

您可以通过创建 File 对象并使用 exists 方法来检查文件是否存在。与 C 相比,Java 中的文件对象不同,创建文件对象时不一定要创建物理文件。

File file = new File(pathString);
if (file.exists())
{
    //  File already exists
}
else
{
    //  You can create your new file
}

【讨论】:

    【解决方案2】:

    我认为你可以在你的 if 中使用这个条件:

    Files.exists(Paths.get(file)) 
    

    您可以决定使用规范NOFOLLOW_LINKS 以避免遵循符号链接。

    这将帮助您检查文件是否存在。

    我希望这可以帮助你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多