有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Windows上运行时,使用Filechooser的java选定文件不会显示为选定文件。在OSX上运行完美

我有一个JavaFXGUI程序,它使用filechooser选择pdf,然后在选定的pdf上运行该程序。我在我的Mac电脑上编程,但是我的一个用户在windows上。Mac上的一切都按预期运行,但当您在windows上单击程序中的“选择PDF”按钮时,目录会按预期打开,但当您选择文件并单击“确定”时,不会返回所选内容

 selectBtn.setOnAction(e -> {
        //Select PDF's Button
        System.out.println("SelectBtn"); //Press to select all ICP-MS PDF files you want to analyze

        //opens file directory to find and select PDF Files
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select PDF Files");

        fileChooser.getExtensionFilters().addAll(new ExtensionFilter("PDF Files", "*.pdf"));
        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(savedStage);

        for (File selectedFile : selectedFiles) {  // gets all of the path's to selected files and saves them as a string
            String tempFilePath = selectedFile.getAbsolutePath();
            System.out.println(tempFilePath);
            selStrings.add(tempFilePath);
        }

        //shortening up the listview path, need to update list view using this then add a button to increase or decrease the size of path
        for (int i= 0; i < selStrings.size(); i++) {
            String tempFilePath = selStrings.get(i);
            String result[] = tempFilePath.split("/");
            String slash = "/"; 
            String shortFilePath = result[result.length - 3] + slash + result[result.length - 2] + slash + result[result.length - 1];
            shortStrings.add(shortFilePath);
            System.out.println(shortFilePath);
        }

        Collections.sort(selStrings);
        Collections.sort(shortStrings);//sorts alphabetically for initial view in listview
        refreshListView();
    });

知道是什么导致了这一切吗?不过,我希望JVM在这两种平台上都能正常工作


共 (1) 个答案

  1. # 1 楼答案

    我建议您使用:

    String slash = FileSystems.getDefault().getSeparator();
    String result[] = tempFilePath.split(slash);
    String shortFilePath = result[result.length - 3] + slash + result[result.length - 2] + slash + result[result.length - 1];
    

    通过这种方式,您可以获得独立于操作系统的Fileseparator字符,它肯定适用于所有操作系统。我认为windows不喜欢普通的“/”并且通常使用“\”而不是MacOS X

    我希望我能帮助你:)