现在,我可以保存基于我在Java Swing中制作的文字处理器的文件。当他们按下保存按钮时,JFileChooser
询问他们要将其保存到何处。我希望这样,以便每次用户保存时,都会在lib
文件夹中生成一个备份,以便用户可以还原到以前的副本。有什么办法可以说为用户拥有的每个文件在bin
文件夹中生成一个文件夹,然后在该文件夹中生成副本。例如,用户创建一个名为MyDoc.rtf
的文件,并且在lib
内部生成一个名为MyDoc
的文件夹,并且内部具有已保存版本copy1
,copy2,
,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");
}
}
}
}
为了创建尚不存在的目录,我可以简单地执行mkdirs()
,然后使用Files
写入路径。另外,我可以使用FileWriter
,BufferedWriter
和FileOutputStream
。
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();
}