简体   繁体   English

如何将Java项目导出到具有资源的可运行jar?

[英]How to export Java project to runnable jar with resources?

I would like to ask how to properly export Java project in IntelliJ IDEA to runnable jar file? 我想问一下如何正确地将IntelliJ IDEA中的Java项目导出到可运行的jar文件? My attempt exporting: Project Structure -> Artifacts -> "+" -> Javafx Application -> From module 'xyz', in tab "JavaFX" I write application class and change "Native bundle" to "all". 我尝试导出:项目结构->工件->“ +”-> Javafx应用程序->从模块'xyz'的“ JavaFX”选项卡中,我编写应用程序类并将“本机包”更改为“全部”。 After that I am building project. 之后,我正在构建项目。

Structure: 结构体:

project  
├── out  
│    └── ...  
├── src (marked as root folder)  
│    └── sample  
│         ├── resources (marked as resources folder)  
│         |   └──some txt file  
│         ├── Main.java  
│         ├── Controller.java  
│         └── layout.fxml 

In main java I am trying to get txt file using 在主java中,我试图使用
new File(getClass().getClassLoader().getResource("file.txt").getFile()) While compilinf project in IDE everything is OK, but after exporting and running jar file the program can't find txt file. new File(getClass().getClassLoader().getResource("file.txt").getFile())在IDE中编译项目时一切正常,但是在导出并运行jar文件后,程序找不到txt文件。 The same problem is when the resources folder is inside in "project" (the same level as src folder). 同样的问题是资源文件夹位于“项目”(与src文件夹处于同一级别)中时。

Thanks in advance! 提前致谢!

If you are exporting the project as is into a jar file the input file will be in the resources folder. 如果要将项目直接导出到jar文件中,则输入文件将位于resources文件夹中。

Try changing the code to something like 尝试将代码更改为类似

new File(getClass().getClassLoader().getResource("resources/file.txt").getFile())

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

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