首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查文件是否退出,那么创建新文件的过程是什么?

如何检查文件是否退出,那么创建新文件的过程是什么?
EN

Stack Overflow用户
提问于 2016-03-01 14:00:32
回答 1查看 303关注 0票数 1

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

代码语言:javascript
复制
    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) {

        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-01 14:49:50

代码语言:javascript
复制
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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35724946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档