Search code examples
javafxfilepathfilechooser

Using Filechooser in JavaFX to Find A File Then Save It's Path As A String


I was wondering if it is possible to use a Filechooser in JavaFX to locate a file, then when I click "open" in the Filechooser it would somehow record the file path of that file as a String?

I've looked around online on how to do this but haven't seen any explanation. If someone could show me some sample code of how to do this it would be very appreciated :)


Solution

  • The FileChooser returns a File:

    File file = chooser.showOpenDialog(stage);
    

    You can just call toString() on the file to get the file as a string value:

    if (file != null) {
        String fileAsString = file.toString();
        . . .
    }
    

    selection

    Sample App

    import javafx.application.Application;
    import javafx.geometry.*;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.VBox;
    import javafx.stage.FileChooser;
    import javafx.stage.Stage;
    
    import java.io.File;
    
    public class SavePath extends Application {
    
        @Override
        public void start(final Stage stage) throws Exception {
            Button button = new Button("Choose");
            Label chosen = new Label();
            button.setOnAction(event -> {
                FileChooser chooser = new FileChooser();
                File file = chooser.showOpenDialog(stage);
                if (file != null) {
                    String fileAsString = file.toString();
    
                    chosen.setText("Chosen: " + fileAsString);
                } else {
                    chosen.setText(null);
                }
            });
    
            VBox layout = new VBox(10, button, chosen);
            layout.setMinWidth(400);
            layout.setAlignment(Pos.CENTER);
            layout.setPadding(new Insets(10));
            stage.setScene(new Scene(layout));
            stage.show();
        }
    
        public static void main(String[] args) throws Exception {
            launch(args);
        }
    }