0

in this program, im trying to select a file and read the relative path to the project of this file

        FileChooser photo = new FileChooser();
        Stage stage = new Stage();stage.setTitle("File Chooser Sample");
        openButton.setOnAction((final ActionEvent t) -> {
            File file = photo.showOpenDialog(stage);
            if (file != null) {
                System.out.println(file.getPath());;
            }
        });

the path of my project is C:\Users\151\eclipse-workspace\FlexiRentGui\

and i'm running the program in eclipse ide

when i select C:\Users\151\eclipse-workspace\FlexiRentGui\res\1.jpg

instead of printing the relative path "/res/1.jpg"

it still prints the absolute path C:\Users\151\eclipse-workspace\FlexiRentGui\res\1.jpg

Eric Yu
  • 27
  • 9

2 Answers2

1

You need to get URI of your current directory/project's root directory and then use java.net.URI.relativize() method to find the relative path of the chosen file w.r.t your project's root. Something like this: new File(cwd).toURI().relativize(file.toURI()).getPath().

Here is the psuedo code:

package org.test;

import java.io.File;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class FileChooserDemo extends Application {

    public FileChooserDemo() {};

    public static void main(String[] args) throws ClassNotFoundException {
        FileChooserDemo.launch(FileChooserDemo.class); 
    }

    public void chooseFileAndPrintRelativePath() {
        FileChooser photo = new FileChooser();
        Stage stage = new Stage();
        stage.setTitle("File Chooser Sample");
        Button openButton = new Button("Choose file");
        openButton.setOnAction((t) -> {
            File file = photo.showOpenDialog(stage);
            if (file != null) {
                String cwd = System. getProperty("user.dir");
                System.out.println(new File(cwd).toURI().relativize(file.toURI()).getPath());
            }
        });
        //Creating a Grid Pane 
        GridPane gridPane = new GridPane();    
        //Setting size for the pane 
        gridPane.setMinSize(400, 200);
        gridPane.add(openButton, 0, 0); 
        Scene scene = new Scene(gridPane);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        chooseFileAndPrintRelativePath();
    }

}
ImGroot
  • 796
  • 1
  • 6
  • 17
0

You can avoid using the old java.io package and use java.nio instead. Your code will look a bit better and will be much shorter (also using the new library).

To do so just get the current working directory:

var pwd = Paths.get("").toAbsolutePath();
var relative = pwd.relativize(Paths.get("someOtherPath"));

I hope this helps.

akortex
  • 5,067
  • 2
  • 25
  • 57