Save files with JavaFX FileChooser

JavaFX FileChooser save dialog
JavaFX FileChooser save dialog

JavaFX provides javafx.stage.FileChooser class for creating file chooser dialog to select files for opening or saving. The major advantage of javafx filechooser over old JFileChooser is that, it allows to use the default system chooser. So, if you use the FileChooser in linux, then linux’s default file chooser window will be loaded and in windows, windows’s default file chooser window will be loaded. This helps to improve the user experience by a huge margin. The old JFileChooser had a fixed dialog that was very hard to navigate and this problem is fixed in JavaFX.

Let’s see a sample program that shows file chooser to create a text file and save a string to that file.

package javafxtutorials;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;


public class SaveFileWithFileChooser extends Application {

    @Override
    public void start(final Stage primaryStage) {
        final String sampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut \n"
                + "labore et dolore magna aliqua.\n"
                + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n"
                + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n"
                + "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

        Text sample = new Text(sampleText);
        sample.setFont(new Font(14));

        Button btnSave = new Button("Save");

        btnSave.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();

            //Set extension filter for text files
            FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
            fileChooser.getExtensionFilters().add(extFilter);

            //Show save file dialog
            File file = fileChooser.showSaveDialog(primaryStage);

            if (file != null) {
                saveTextToFile(sampleText, file);
            }
        });

        VBox vBox = new VBox(sample, btnSave);
        vBox.setAlignment(Pos.CENTER);

        primaryStage.setScene(new Scene(vBox, 800, 300));
        primaryStage.setTitle("www.genuinecoder.com");
        primaryStage.show();

    }

    private void saveTextToFile(String content, File file) {
        try {
            PrintWriter writer;
            writer = new PrintWriter(file);
            writer.println(content);
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(SaveFileWithFileChooser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}

 

JavaFX FileChooser program
JavaFX FileChooser program

The FileChooser.ExtensionFilter defines an extension filter which can be used for filtering which files can be chosen in a FileDialog based on the file name extensions. The constructor takes two arguments. First argument is the description of file to be selected and second argument is the actual extension. The second argument can also be a list.

By calling the FileChooser#showSaveDialog, a save dialog will be opened. In this case, the dialog will only show directories and text files. Once a file name is specified and save button is pressed, method saveTextToFile will be called which will save the text content to file with the help of PrintWriter class.

JavaFX FileChooser save dialog
JavaFX FileChooser save dialog in Linux Mint 18.2
 if (file != null) {
    saveTextToFile(sampleText, file);
 }

If the user clicks on the cancel button from the file chooser instead of save button, the returned file will be null. So, it is always necessary to check for null case for the returned file which otherwise will leads to NullPointerException.

Muhammed Afsal Villan
Muhammed Afsal Villan is an experienced full-stack developer, specialized in desktop and mobile application development. He also regularly publishes quality tutorials on his YouTube channel named 'Genuine Coder'. He likes to contribute to open-source projects and is always enthusiastic about new technologies.

5 COMMENTS