繁体   English   中英

加载存储在jar文件中的文件

[英]Load a file that stored inside a jar file

我的项目中的myproject / fxml / myScreen.fxml中有一个FXML文件,我尝试使用FXMLLoader加载它:

content.getChildren().setAll(FXMLLoader.load(new URL("myproject/fxml/myScreen.fxml")));

但是后来我得到了这个例外,

`java.net.MalformedURLException: no protocol: myproject/fxml/myScreen.fxml`

有人可以告诉我我哪里错了吗?
谢谢。

让您的ClassLoader作为资源加载它(假设jar在您的类路径中/使用与当前类相同的类加载器),并将其作为流提供:

content.getChildren().setAll(FXMLLoader.load(this.getClass().getResourceAsStream("myproject/fxml/myScreen.fxml")));

由于未在传递给URL()的参数中定义协议 ,因此出现错误。

它通常接受HTTP/File地址。 如果要加载文件,则应在字符串中添加file:前缀。

可以使用以下正确的方法来加载本地计算机中存在的文件:

FXMLLoader.load(new URL("file://myproject/fxml/myScreen.fxml"));

最好的办法

要加载jar中存在的文件,最好的方法是在FXMLLoader.load()中使用getClass.getResource(PATH_TO_FXML)

由于您是直接加载fxml并将其分配给内容,因此必须使用FXMLLoader的非静态load()

FXMLLoader loader = new FXMLLoader(getClass().getResource("/myproject/fxml/myScreen.fxml"));
content.getChildren().setAll(loader.load());

根据Oracle文档: 示例

public static void main(String[] args) {
    Application.launch(FXMLExample.class, args);
}

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));

    stage.setTitle("FXML Welcome");
    stage.setScene(new Scene(root, 300, 275));
    stage.show();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM