【问题标题】:How to see if a file with the same name already exists [duplicate]如何查看同名文件是否已经存在[重复]
【发布时间】:2021-12-19 16:06:48
【问题描述】:

我试图做的是查看文件夹中是否已经存在同名文件。我曾尝试使用 file.exists 方法,但它只说明文件夹中是否存在文件。

if (option == JFileChooser.APPROVE_OPTION) {
    file = new File(fileChooser.getSelectedFile().toString() + ".html");

    try {
        FileWriter writer = new FileWriter(file);
        if (file.exists()) {
            int ergebnis = JOptionPane.showConfirmDialog(TiltungsplanGUI.this,
                    "The File exists already. Overwrite?", "Meldung",
                    JOptionPane.YES_NO_OPTION);
            if (ergebnis == JOptionPane.YES_OPTION) {
                writer.write(r.getTilgungsplan());
            }
        }

        writer.close();

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(TiltungsplanGUI.this, e1.getMessage());
    } catch (RatenRechnerException e1) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(TiltungsplanGUI.this, e1.getMessage());
    }

}

【问题讨论】:

标签: java file


【解决方案1】:
new FileWriter(file)

创建文件。刚创建完再去检查它是否存在是很荒谬的。

您可能希望在创建 FileWriter 之前移动支票...

【讨论】:

  • 竞态条件如何?
  • 好点。如果可以进行比赛,我会使用Files.newBufferedWriter(path, charset, StandardOpenOption.CREATE_NEW) 来创建文件,前提是它尚不存在。
猜你喜欢
  • 2017-04-27
  • 2021-11-28
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多