Open and Save File Classes using JAVA

Here's a java class that will handle basic opening and saving of files with the use of a JFileChooser.

/**********************************************************************************/
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.io.*;

public class OpenSaveFile {


public OpenSaveFile() {
// TODO: Add your code here
}

public static File getFile(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("C:\\Users\\vista2\\Documents\\mel\\work and play\\masters\\gme202\\labex3\\TwoDConformal\\"));

int result = fileChooser.showOpenDialog( null );

// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION ){

JOptionPane.showMessageDialog( null, "Bye",
"Cancel", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}

File fileName = fileChooser.getSelectedFile(); // get selected file

// display error if invalid
if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
{
JOptionPane.showMessageDialog( null, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end if

return fileName;
}

public static File SaveFile(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("C:\\Users\\vista2\\Documents\\mel\\work and play\\masters\\gme202\\labex3\\TwoDConformal\\"));
fileChooser.setDialogTitle("Save your output file");
int result = fileChooser.showSaveDialog( null );

// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION ){

JOptionPane.showMessageDialog( null, "Bye",
"Cancel", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}

File fileName = fileChooser.getSelectedFile(); // get selected file

// display error if invalid
if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
{
JOptionPane.showMessageDialog( null, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end if

return fileName;
}
}
/************************************************************************************/

Comments

Popular posts from this blog

Free Open Street Map data (i.e.shapefiles etc.) for the Philippines

Free Philippine Administrative Boundaries shapefile

University of the Philippines Diliman Campus