现在,我可以基于用 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();
}
关于java - 在Java Swing中,有没有办法将文件保存到某种 'lib'文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58938272/