【问题标题】:How to check if a file is exits then what is the process to create new file? [duplicate]如何检查文件是否存在,那么创建新文件的过程是什么? [复制]
【发布时间】:2016-06-13 23:47:12
【问题描述】:

我正在使用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) {

        }
    }

【问题讨论】:

  • 也许看看File.exists()之类的东西。
  • 但是先生,我的问题是如何找出将已经生成的pdf文件和新生成的文件与位置进行比较的位置。
  • File.equals(File)?我很难理解你的意思。也许从用户的角度解释会发生什么会更好。例如。 1) 用户生成并保存 PDF 2) 用户在编辑器中创建新 PDF。 3)用户去保存旧PDF上的新PDF。 4) ..那应该发生什么?
  • 用户要求是他第一次使用 jfilechooser 创建 pdf 时,如果另一个用户创建像 d 一样的名称,他们会在 5 分钟后在指定位置(如 d:\test.pdf)给出 pdf 的名称: \test.pdf 然后他们显示类似 joptionpane 的消息框以显示名称已退出,请为 pdf 选择另一个名称。

标签: java swing jfilechooser


【解决方案1】:
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();
}

【讨论】:

  • JOptionPane.showMessageDialog(this, "Please choose another file."); return; 如果我是用户,我希望得到提示。更像是.. int result = JOptionPane.showConfirmDialog(this, "Sure you want to overwrite?"); if (result==JOptionPane.OK_OPTION) { .. } else { ..
  • 只是想向他展示如何检查所选文件是否存在于该上下文中(我猜这是主要问题)。
  • 但首先如何检查生成的 pdf 文件路径和新的创建文件路径,我使用的是 if(chooserobj.getSelectedFile(),getselectedpath==???){joptionpane.showmessagedialog(this,"name已退出,请选择其他名称")} 但此代码不起作用
  • 请帮我解决这个问题]'
  • 请发给我找出这个问题的逻辑?
猜你喜欢
  • 2013-07-22
  • 2018-09-27
  • 1970-01-01
  • 2013-04-20
  • 2020-02-03
  • 2011-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多