Java代码在Netbeans IDE中构建和清理后找不到资源文件? [英] Java code cannot find resource file after build and clean in Netbeans IDE?
问题描述
在构建代码项目后,我在dist目录中得到一个jar文件。我运行它。由于应用程序使用JFrame作为用户界面,所以它正常打开。但是,当我执行该应用程序的某些功能时,它显示了错误日志。这里是错误信息:
pre $ java.io.FileNotFoundException:
src\sample.xlsx(系统不能找到指定的路径)
有什么问题吗?
以下是我的一些代码:
$ $ $ $ $ $ copyFile(new File(src \\sample。 xlsx),
new File(txtout.getText()+\\sample.xlsx));
节点: copyFile函数用于从源文件复制到目标文件。
这是我在Netbean IDE中的项目文件夹结构:
$ b $ ol
- 源代码包(src)
- myClass.java,sample.xlsx等
解决方案永远不要直接引用
src
,程序一旦建立,目录就不存在。其次,您不能通过File
引用来访问嵌入在应用程序上下文中的资源,它们在文件系统上不再存在。
相反,您需要使用
Class#getResource
或Class#getResourceAsStream
URL url = getClass()。getResource(/ sample.xlsx);
InputStream is = getClass()。getResourceAsStream(/ sample.xlsx);
//不要忘记适当地管理你的流...
I really need your help to solve my own problem. Now, I'm dealing with small code app. In that project folder contain some resource files (*.xlsx, *.png,...). I placed them in current folder with code file. I just wonder that when I run my code in netbean ide, it just worked find.
After I build code project, I get a jar file in "dist" directory. I run it. It open normally since app used JFrame as user interface. However, when I execute some function of that app, it showed me the error log. Here is the error message:
java.io.FileNotFoundException: src\sample.xlsx (The system cannot find the path specified)
What's the matter out there?
Here is some pieces of my code:
copyFile(new File("src\\sample.xlsx"), new File(txtout.getText()+"\\sample.xlsx"));
Node: copyFile function is used for copy file from source to dest.
Here is my project folder structure in Netbean IDE:
- Project Name
- Source Pakage(src)
- myClass.java, sample.xlsx, etc
- Source Pakage(src)
解决方案First, never reference
src
directly, the directory will not exist once the program is built. Second, you can not access resources which have been embedded within in the application context via aFile
reference, they simply no longer exist on the file system.Instead, you need to use
Class#getResource
orClass#getResourceAsStream
URL url = getClass().getResource("/sample.xlsx"); InputStream is = getClass().getResourceAsStream("/sample.xlsx"); // Don't forget to manage your streams appropriately...
这篇关于Java代码在Netbeans IDE中构建和清理后找不到资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- myClass.java,sample.xlsx等