在Java Swing中,是否可以将文件保存到某种'lib'文件夹中?

问题描述 投票:0回答:1

现在,我可以保存基于我在Java Swing中制作的文字处理器的文件。当他们按下保存按钮时,JFileChooser询问他们要将其保存到何处。我希望这样,以便每次用户保存时,都会在lib文件夹中生成一个备份,以便用户可以还原到以前的副本。有什么办法可以说为用户拥有的每个文件在bin文件夹中生成一个文件夹,然后在该文件夹中生成副本。例如,用户创建一个名为MyDoc.rtf的文件,并且在lib内部生成一个名为MyDoc的文件夹,并且内部具有已保存版本copy1copy2,copy3等的所有副本

所以,这个问题有两个部分。如何为每个保存的文件生成一个缓存文件夹?以及如何生成这些副本?

我使用JFileChooser保存文件的方式如下

public class SaveContent {
String formattedText;

public void save(JTextPane text){
    if(text.getText().length() > 0){
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("RICH TEXT FORMAT", "rtf", "rtf");
        chooser.setFileFilter(filter);

        int option = chooser.showSaveDialog(null);
        String filePath = chooser.getSelectedFile().getPath();

        if(!chooser.getSelectedFile().getPath().toLowerCase().endsWith(".rtf")){
            filePath=chooser.getSelectedFile().getPath() + ".rtf";
        }

        if(option == JFileChooser.APPROVE_OPTION){
            StyledDocument doc = (StyledDocument)text.getDocument();
            HTMLEditorKit kit = new HTMLEditorKit();
            BufferedOutputStream out;

            try{
                out = new BufferedOutputStream(new FileOutputStream(filePath));
                kit.write(out,doc,doc.getStartPosition().getOffset(), doc.getLength());
            } catch(FileNotFoundException e){

            } catch(IOException e){

            } catch(BadLocationException e){

            }
        } else{
            System.out.println("SAVE CANCCELED");
        }
    }
}

}

java swing jfilechooser
1个回答
0
投票

为了创建尚不存在的目录,我可以简单地执行mkdirs(),然后使用Files写入路径。另外,我可以使用FileWriterBufferedWriterFileOutputStream

          if(textListiner != null) {
                textListiner.textEmitted("GOodeye\n");

                //Add a folder
                File f = new File("../Swing1/backups/testDir");
                if(!f.exists()) {
                    boolean success = (new File("../Swing1/backups/testDir")).mkdirs();
                    if (!success) {
                        // Directory creation failed
                        System.out.println("FAIL CREATE DIR");
                    }
                }
                else {
                    System.out.println("ALREADY EXISTS");
                }               
            }

                //Add the file to the folder (without JFileChooser and showSaveDialog)
                // COuld use FileWriter, BufferedWriter FIleOutputStream, or Files
                //Lookup: https://www.journaldev.com/878/java-write-to-file
                String data;
                try {
                    Files.write(Paths.get("../Swing1/backups/testDir/copy1.txt"), data.getBytes());
                } catch (IOException eIO) {
                    eIO.printStackTrace();
                }
© www.soinside.com 2019 - 2024. All rights reserved.