如何检查文件是否存在然后创建新文件的过程是什么?

How to check if a file is exits then what is the process to create new file?

我正在使用 JFileChooser 在指定的文件位置生成 PDF 文件,但我的要求是当我们在 d 驱动器位置生成类似 d:\test.pdf** 的 PDF 时,我们再次尝试生成相同的 PDF 文件 **它覆盖以前的 PDF 文件要求是他们显示消息框以表明它已经生成并生成另一个 PDF 文件 name.like test1.pdf 我的问题 代码:申请按钮

    JFileChooser dialog = new JFileChooser();
//            chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        dialog.setCurrentDirectory(new java.io.File("."));
        dialog.setDialogTitle("Save Backup");
        dialog.setApproveButtonText("Save");
        //disables the all filesoptioning here
        dialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        dialog.setAcceptAllFileFilterUsed(false);

        if (dialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            System.out.println("getCurrentDirectory(): " + dialog.getCurrentDirectory());
            System.out.print("getSelectedFile() : " + dialog.getSelectedFile());

            try {
                String filePath = dialog.getSelectedFile().getPath();
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(filePath));
                document.open();
                document.add(new Paragraph(" hello"));
                document.close();
        } catch (Exception e) {

        }
    }
if (dialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
    File selectedFile = dialog.getSelectedFile();

    if (selectedFile.exists()) {
        JOptionPane.showMessageDialog(this, "Please choose another file.");
        return;
    }

    PdfWriter.getInstance(document, new FileOutputStream(selectedFile));
    document.open();
    document.add(new Paragraph(" hello"));
    document.close();
}