Java无法识别JAR中的文件 [英] Java won't recognize file in JAR
问题描述
我的Java程序的JAR文件中有一个.csv数据库文件.在打包之前,该程序可以在NetBeans IDE中正常运行,但是一旦这样做,它就不会相信文件在其中,即使我已将其打印出查找的路径并解压缩JAR以确保我告诉了它.找对地方.我如何让Java看到这一点?
I have a .csv database file inside my java program's JAR file. The program works fine in NetBeans IDE before I package it, but once I do, it refuses to believe the file is in it, even though I had it print out the path where it was looking and unzipped the JAR to be sure I told it to look in the right place. How do I make Java see this?
try
{
String path = Main.class.getResource("/items.csv").getPath();
db = new java.io.File(path);
loadValues(db);
}
catch (java.io.FileNotFoundException ex1)
{
System.out.println("Could not find database file (" + ui.db + ").");
}
推荐答案
不要为资源创建File
对象,因为可能没有File
. File
表示文件系统上仅 个真实"文件.就操作系统而言,.jar文件中的文件"只是一些字节.
Don't create a File
object for the resource, as there may be no File
. A File
represents only "real" files on the filesystem. As far as the OS is concerned a "file" inside a .jar file is just some bytes.
您需要使用 getResourceAsStream()
来获取InputStream
并从中读取.
You'll need to use getResourceAsStream()
to get an InputStream
and read from that.
这篇关于Java无法识别JAR中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!