|
| 1 | +import javafx.stage.FileChooser; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | + |
| 5 | +public class Operator { |
| 6 | + public static final String[] EXTENSIONS = new String[] {"pew"}; |
| 7 | + public static final String DEFAULT_EXTENSION = EXTENSIONS[0]; |
| 8 | + public static final String[] MIME_TYPES = new String[] {"public.data, com.example.pew"}; |
| 9 | + public static final String DEFAULT_FOLDER = "/Users/Shared"; |
| 10 | + |
| 11 | + private static File openFile = null; |
| 12 | + |
| 13 | + private Operator() {} |
| 14 | + |
| 15 | + public static File getOpenFile() { |
| 16 | + return openFile; |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * Checks whether an input parameter is a path to a valid file. |
| 21 | + * |
| 22 | + * @param input Console input parameter. |
| 23 | + * @return True if input was path to a valid file. |
| 24 | + */ |
| 25 | + public static boolean parseInput(String input) { |
| 26 | + File file = new File(input); |
| 27 | + |
| 28 | + if (!file.exists() || file.isDirectory()) { |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + boolean validExtension = false; |
| 33 | + for (String ext : EXTENSIONS) { |
| 34 | + if (!file.getName().endsWith(ext)) continue; |
| 35 | + validExtension = true; |
| 36 | + break; |
| 37 | + } |
| 38 | + |
| 39 | + if (!validExtension) return false; |
| 40 | + |
| 41 | + openFile = file; |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Prompts the user to choose a file from storage. |
| 47 | + * |
| 48 | + * @return True if successfully found a file. |
| 49 | + */ |
| 50 | + public static boolean chooseNewFile() { |
| 51 | + FileChooser fileChooser = new FileChooser(); |
| 52 | + |
| 53 | + // Start from existing directory |
| 54 | + if (getOpenFile() != null) { |
| 55 | + fileChooser.setInitialDirectory(openFile.getParentFile()); |
| 56 | + } else { |
| 57 | + File dir = new File(DEFAULT_FOLDER); |
| 58 | + if (dir.exists() && dir.isDirectory()) { |
| 59 | + fileChooser.setInitialDirectory(dir); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Set extension filter |
| 64 | + for (String extension : EXTENSIONS) { |
| 65 | + fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter( |
| 66 | + extension + " files", "*." + extension |
| 67 | + )); |
| 68 | + } |
| 69 | + |
| 70 | + // Show open file dialog |
| 71 | + File candidateFile = fileChooser.showOpenDialog(null); |
| 72 | + if (candidateFile == null) return false; |
| 73 | + |
| 74 | + // Parse chosen file |
| 75 | + return parseInput(candidateFile.getAbsolutePath()); |
| 76 | + } |
| 77 | +} |
0 commit comments