16

I'm trying to save a file using JFileChooser. However, I seem to be having some trouble with it. Here's my code:

    if (e.getSource() == saveMenu) {

        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
        // add filters
        chooser.addChoosableFileFilter(xmlFilter);
        chooser.setFileFilter(xmlFilter);

        int result = chooser.showSaveDialog(Simulation.this);

        if (result == chooser.APPROVE_OPTION) {
            writeToXML(chooser.getSelectedFile());
        }

    }

This doesn't force the file to have a .xml extension, so I've tried to use the following code to force the file to be saved with the extension .xml

     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("UTF-8");
     XMLWriter xmlWriter = null;
     try {              
         xmlWriter = new XMLWriter(new OutputStreamWriter(
                 new FileOutputStream(f+".xml"), "UTF8"),
                 format);

However, with this I can't prevent the user from writing xpto.xml in the JFileChooser and if they do that, the file will have "two extensions": it will be a file named xpto.xml.xml

So my questions are:

  • How can I make the JFileChooser save an xml file by default?
  • If the user inserts a file name like xpto.xml, how can I save it as xpto.xml and not xpto.xml.xml?
4

5 回答 5

20

正如您所注意到JFileChooser的,不会强制FileFilter保存。它将在它显示的对话框中灰显现有的非 XML 文件,但仅此而已。要强制执行文件名,您必须完成所有工作。(这不仅仅是 JFileChooser 糟糕的问题——这是一个需要处理的复杂问题。您可能希望您的用户能够命名他们的文件xml.xml.xml.xml。)

在您的情况下,我建议使用FilenameUtilsCommons IO:

File file = chooser.getSelectedFile();
if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("xml")) {
    // filename is OK as-is
} else {
    file = new File(file.toString() + ".xml");  // append .xml if "foo.jpg.xml" is OK
    file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".xml"); // ALTERNATIVELY: remove the extension (if any) and replace it with ".xml"
}

如果您在此处的保存对话框中需要多种类型,也有一些想法:如何使用 JFileChooser 保存文件?

于 2013-06-09T15:17:54.157 回答
12

只是为了说明如何使用 JFileChooser 来保存文件。

//set it to be a save dialog
 chooser.setDialogType(JFileChooser.SAVE_DIALOG);
//set a default filename (this is where you default extension first comes in)
 chooser.setSelectedFile(new File("myfile.xml"));
//Set an extension filter, so the user sees other XML files
 chooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));

现在,在本例中鼓励用户将项目保存为 xml 文件,但他们可能没有实际设置它。

if(chooser.showSaveDialog(this) == jFileChooser.APPROVE_OPTION) {
    String filename = chooser.getSelectedFile().toString();
    if (!filename .endsWith(".xml"))
        filename += ".xml";

    //DO something with filename
}

这是最简单的情况,如果您有多种可能的文件格式,那么您应该捕获选定的过滤器,验证 THAT 扩展名,并根据选定的格式保存文件。但如果你这样做,你可能是一个高级 Java 程序员,并且没有使用这篇文章。

于 2015-07-24T19:50:16.383 回答
3

像这样的东西怎么样:

    else if (e.getSource() == saveMenu) {
        int returnVal = chooser.showSaveDialog(Simulator.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();

            String fname = file.getAbsolutePath();

            if(!fname.endsWith(".xml") ) {
                file = new File(fname + ".xml");

            if(!file.createNewFile()) {
                /*check with user??*/
            }
于 2013-06-09T15:34:10.817 回答
1

你应该试试这个:

if(!file.getName().contains(".")) file = new File(file.toString() + ".xml");
于 2017-09-20T16:02:20.847 回答
0

你应该试试这个。我这样做了,它奏效了。

FileOutputStream fileOut =  new FileOutputStream(file1+".xml");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
于 2015-04-14T18:58:37.553 回答