gpt4 book ai didi

java - JFileChooser 使用扩展名保存

转载 作者:行者123 更新时间:2023-12-02 10:59:54 30 4
gpt4 key购买 nike

我创建了一个文件,然后需要将其另存为 .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);

最佳答案

 // 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);

关于java - JFileChooser 使用扩展名保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51416246/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com