RCP Open and Save File Dialogs

I'm currently developing an Eclipse application, and since some of the usual functionalities is the open and save file, or project, I'm posting here a nice code snippet for using open and save dialogs in Rich Client Platform (RCP) applications.

Both the FileOpen and FileSave classes bellow are ready for usage as a command default handler for the extension org.eclipse.ui.commands in the plugin.xml file. Don't forget to create the menu entry to use this command.

Here's the open file snippet (don't forget to update the package)
package your.package.in.here;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

/**
* Opens a file
*/
public class FileOpen extends AbstractHandler implements IHandler {

@Override
public Object execute(ExecutionEvent event)
throws ExecutionException {

Shell shell = PlatformUI.getWorkbench().
getActiveWorkbenchWindow().getShell();

FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.txt", "*.*"});
dialog.setFilterNames(new String[] {"Text File", "All Files"});
String fileSelected = dialog.open();

if (fileSelected != null) {
// Perform Action, like open the file.
System.out.println("Selected file: " + fileSelected);
}
return null;
}
}


And here's the save file snippet (don't forget to update the package):
package your.package.in.here;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

/**
* Save file as...
*/
public class ProjectFileAs extends AbstractHandler implements IHandler {

@Override
public Object execute(ExecutionEvent event)
throws ExecutionException {
Shell shell = PlatformUI.getWorkbench().
getActiveWorkbenchWindow().getShell();

FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.txt", "*.*"});
dialog.setFilterNames(new String[] {"Text File", "All Files"});
String fileSelected = dialog.open();

if (fileSelected != null) {
// Perform Action, like save the file.
System.out.println("Selected file: " + fileSelected);
}
return null;
}
}

./M6