0

我正在编写一个有多个用户的程序,并且我希望每个用户都能够使用他们选择的文件名保存文件,但是,还将他们的用户名或相关键附加到文件名以帮助稍后进行搜索。我该如何调整此代码来做到这一点?

例如,用户“bob”想要将文件保存为“aFile.html”。我要实际保存的文件是“aFile_bob.html”

    String user = "bob";
    // select a file to save output
    JFileChooser JfileChooser = new JFileChooser(new File(defaultDirectory));
    JfileChooser.setSelectedFile(new File("TestFile.html"));
    int i = JfileChooser.showSaveDialog(null);
    if (i != JFileChooser.APPROVE_OPTION) return;
    File saveFile = JfileChooser.getSelectedFile();
    // somehow append "user" to saveFile name here?

    FileOutputStream fop = new FileOutputStream(saveFile);
4

1 回答 1

1

使用renameTo方法,如下所示:

int lastDot = saveFile.getName().lastIndexOf('.');
String name = saveFile.getName();
String ext = ""; // Might not have a file extension
if(lastDot > 0) { // At least one dot
    // Take substring of the last occurrence
    ext = saveFile.getName().substring(lastDot);
    name = name.substring(0, lastDot);
}

saveFile.renameTo(new File(defaultDirectory + "/" + name + "_" + user + ext));

使用此方法,您不需要 FileOutputStream。

于 2012-11-14T19:31:43.790 回答