java - file.getPath() 的相对路径

标签 java eclipse javafx file-handling

在此程序中,我尝试选择一个文件并读取该文件的项目的相对路径

        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());;
            }
        });

我的项目路径是 C:\Users\151\eclipse-workspace\FlexiRentGui\

我正在 eclipse ide 中运行该程序

当我选择 C:\Users\151\eclipse-workspace\FlexiRentGui\res\1.jpg

而不是打印相对路径“/res/1.jpg”

它仍然打印绝对路径 C:\Users\151\eclipse-workspace\FlexiRentGui\res\1.jpg

最佳答案

您需要获取当前目录/项目根目录的 URI,然后使用 java.net.URI.relativize()方法来查找所选文件相对于项目根目录的相对路径。像这样的:new File(cwd).toURI().relativize(file.toURI()).getPath() .

这是伪代码:

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();
    }

}

关于java - file.getPath() 的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52354348/

相关文章:

java - 以编程方式确定耳机插孔的位置

java - 为什么 Java Web Start 要求从 1.7.0_21 开始安装我的应用程序的主要 JAR 和链接组件?

java - 错误消息在 Eclipse 和命令提示符中显示不同

java - Eclipse Neon w/Tomcat 9(新 Servlet)HTTP 状态 404 – 未找到

java - JavaFX调用目标异常-未设置非法状态异常目标

java - 在 html 中嵌入 Javafx

java - 在 JavaFX WebEngine 中禁用图像加载

java - HTTP 错误代码 500

c++ - CDT 中的全局编译器标志

java - 构建测试滑动菜单时出错