CachedFileChooser.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package eu.tankernn.accounts;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import javax.swing.JFileChooser;
  5. public class CachedFileChooser {
  6. public static final JFileChooser FILE_CHOOSER = new JFileChooser("data/");
  7. private static final File lastFilenameCache = new File(System.getProperty("user.home") + File.separator + "accountmanager" + File.separator + "lastFile.txt");
  8. public static File selectFile(boolean saveAs) {
  9. if (getLastFileFromCache() == null)
  10. saveAs = true;
  11. if (saveAs)
  12. FILE_CHOOSER.showDialog(null, "Open/Save");
  13. File f = saveAs ? FILE_CHOOSER.getSelectedFile() : getLastFileFromCache();
  14. writeLastFileToCache(f);
  15. return f;
  16. }
  17. public static File getLastFileFromCache() {
  18. // Open last file
  19. try {
  20. // Create file to cache last filename
  21. if (!lastFilenameCache.exists()) {
  22. return null;
  23. }
  24. String lastFilePath = FileManager.readFileAsString(lastFilenameCache);
  25. File f = new File(lastFilePath);
  26. FILE_CHOOSER.setSelectedFile(f);
  27. return f;
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. return null;
  32. }
  33. static void writeLastFileToCache(File file) {
  34. if (file == null) {
  35. lastFilenameCache.delete();
  36. return;
  37. }
  38. // Remember this filename
  39. if (!lastFilenameCache.equals(file)) { // Don't remember the cache file
  40. lastFilenameCache.getParentFile().mkdirs();
  41. FileManager.saveFile(lastFilenameCache, file.getAbsolutePath());
  42. FILE_CHOOSER.setSelectedFile(file);
  43. }
  44. }
  45. static void clearCache() {
  46. writeLastFileToCache(null);
  47. }
  48. }