Java File Operations
Open a file
First, instantiate JFileChoosers. You can use FileNameExtensionFilter to set the filter. The return value of the showOpenDialog method is of the int type. Therefore, define a value. Finally, if the value is equal to JFileChooser. APPROVE_OPTION can be used to operate the file. The file path is printed here.
private JFileChooser chooser;FileNameExtensionFilter filter = new FileNameExtensionFilter(Allowed File, txt,jar);chooser.setFileFilter(filter);int value = chooser.showOpenDialog(TestOpen.this);if (value == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); System.out.println(file.getAbsolutePath());}
What should I do if I want to open multiple files?
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);chooser.setMultiSelectionEnabled(true);int value = chooser.showOpenDialog(TestOpen.this);if (value == JFileChooser.APPROVE_OPTION) { File file[] = chooser.getSelectedFiles(); for (int i = 0; i < file.length; i++) { System.out.println(file[i].getAbsolutePath()); }}
Save files
To save the file, remember to check for exceptions. An error occurs if you accidentally save the file. Actually, it's nothing more than calling the createNewFile method.
try { JFileChooser chooser = new JFileChooser(); int value = chooser.showSaveDialog(TestSave.this); if (value == JFileChooser.APPROVE_OPTION) { File newfFile = chooser.getSelectedFile(); if (newfFile.exists() == false) { newfFile.createNewFile(); } }} catch (HeadlessException e1) { e1.printStackTrace();} catch (IOException e1) { e1.printStackTrace();}