JFileChooser保存扩展名

时间:2018-07-19 06:59:08

标签: java swing jfilechooser

我创建了一个文件,然后需要将其保存为.docx扩展名,但是我的代码将其保存为.txt,如何更改扩展名?

    JFileChooser saveFile = new JFileChooser();
    saveFile.setDialogTitle("Save a file");
    saveFile.showSaveDialog(null);
    File selectedFile = saveFile.getSelectedFile();

    FileWriter fileWriter = new FileWriter(selectedFile);
    fileWriter.write(editedDoc.toString());
    editedDoc.save(selectedFile.toString(), true);

1 个答案:

答案 0 :(得分:1)

 // sets the file chooser to be able to locate and overwrite .docx file type only
 saveFile.addChoosableFileFilter(new FileNameExtensionFilter("MS Word", "docx")); 

如果用户已经输入了.docx,请使用此代码。

// get the full path of the file
String absolutePath = saveFile.getSelectedFile().getAbsolutePath();  

// does the selected file have an extension of docx?
// if yes then exclude the extension, if no, then add .docx to the file name
if (!absolutePath.substring(absolutePath.lastIndexOf(".")+1).equals("docx"))     
     absolutePath += ".docx";                                                     

FileWriter fileWriter = new FileWriter(absolutePath);
相关问题