//FileChooserDemo.java //demo file open and save dialog windows of JFileChooser import java.io.*; //File import javax.swing.*; //JFileChooser public class FileChooserDemo { public static void main( String[] args ) { File myFile; File myFolder; int status; //GUI widget for file/folder browsing JFileChooser myChooser = new JFileChooser(); //do an Open dialog status = myChooser.showOpenDialog( null );//arg is frame to display in if ( status == JFileChooser.APPROVE_OPTION ) { //means Open clicked //.CANCEL_OPTION is the other Cancel button //determine what was chosen by user: myFile = myChooser.getSelectedFile(); myFolder = myChooser.getCurrentDirectory(); System.out.println( "Selected file: " + myFile.getName() ); System.out.println( "Folder name: " + myFolder.getName() ); System.out.println( "File pathname: " + myFile.getAbsolutePath() ); //now could actually open and read from the file... } System.out.println(); //now do a Save dialog myChooser = new JFileChooser(); status = myChooser.showSaveDialog( null ); //Save and Cancel buttons if ( status == JFileChooser.APPROVE_OPTION ) { //means Save clicked //determine what was chosen by user: myFile = myChooser.getSelectedFile(); myFolder = myChooser.getCurrentDirectory(); System.out.println( "Selected file: " + myFile.getName() ); System.out.println( "Folder name: " + myFolder.getName() ); System.out.println( "File pathname: " + myFile.getAbsolutePath() ); //now could actually open and write to the file...i.e. Save something } System.out.println(); System.out.println(); //seperately from using a JFileChooser, //can determine if a named File exists, or is a file or a folder myFile = new File( "arfarfarf.data" ); //check that the file exists: if ( !myFile.exists() ) System.out.println( "File not found: " + myFile.getName() ); //check that the file is a file (or a folder (i.e. directory)) myFile = new File( "dummyFolder" ); //test with various things if ( myFile.isFile() ) System.out.println( "Is a file: " + myFile.getName() ); else if ( myFile.isDirectory() ) System.out.println( "Is a folder: " + myFile.getName() ); else System.out.println( "Is neither a file nor folder: " + myFile.getName() ); } }