CachedFileChooser.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.showSaveDialog(null);
  13. return saveAs ? FILE_CHOOSER.getSelectedFile() : getLastFileFromCache();
  14. }
  15. private static File getLastFileFromCache() {
  16. // Open last file
  17. try {
  18. // Create file to cache last filename
  19. if (!lastFilenameCache.exists()) {
  20. lastFilenameCache.getParentFile().mkdirs();
  21. lastFilenameCache.createNewFile();
  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. // Remember this filename
  37. if (!file.equals(lastFilenameCache)) { // Don't remember the cache file
  38. FileManager.saveFile(lastFilenameCache, file.getAbsolutePath());
  39. FILE_CHOOSER.setSelectedFile(file);
  40. }
  41. }
  42. static void clearCache() {
  43. writeLastFileToCache(null);
  44. }
  45. }