Java won't recognize file in JAR

橙三吉。 提交于 2021-02-20 04:55:27

问题


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

回答1:


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.

You'll need to use getResourceAsStream() to get an InputStream and read from that.




回答2:


Once you pack it in jar file it is no longer a direct file..

Try to read it with InputStream

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

Also See

  • getResourceAsStream()



回答3:


Use Class.getResourceAsStream to load the files inside the jar:

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

Change your loadValues method to work on an InputStream rather than a File.



来源:https://stackoverflow.com/questions/5217175/java-wont-recognize-file-in-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!