简体   繁体   English

Java无法识别JAR中的文件

[英]Java won't recognize file in JAR

I have a .csv database file inside my java program's JAR file. 我的Java程序的JAR文件中有一个.csv数据库文件。 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. 在打包之前,该程序可以在NetBeans IDE中正常运行,但是一旦这样做,它就不会相信文件在其中,即使我已打印出文件的查找路径并解压缩JAR以确保我告诉了它。找对地方。 How do I make Java see this? 我如何使Java看到这一点?

  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 + ").");
  }

Don't create a File object for the resource, as there may be no File . 不要为资源创建File对象,因为可能没有File A File represents only "real" files on the filesystem. File 表示文件系统上的“实际”文件。 As far as the OS is concerned a "file" inside a .jar file is just some bytes. 就操作系统而言,.jar文件中的“文件”只是一些字节。

You'll need to use getResourceAsStream() to get an InputStream and read from that. 您将需要使用getResourceAsStream()获取InputStream并从中读取。

Once you pack it in jar file it is no longer a direct file.. 将其打包到jar文件中后,它不再是直接文件。

Try to read it with InputStream 尝试使用InputStream读取它

InputStream input = getClass().getRessourceAsStream("/classpath/to/my/items.csv");

Also See 另请参阅

Use Class.getResourceAsStream to load the files inside the jar: 使用Class.getResourceAsStream加载jar中的文件:

    InputStream is = Main.class.getResourceAsStream("/items.csv");
    loadValues(is);

Change your loadValues method to work on an InputStream rather than a File . 更改您的loadValues方法以在InputStream而不是File

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

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