How to read a file from the JAR?

Someone just asked me this question today. And I thought might as well put it down for info.

  1.  public TestReadFileFromJar() throws FileNotFoundException, IOException {
  2.         InputStream is = getClass().getResource("txtData/states.properties");
  3.         read(is);
  4. }

In the case above txtData is placed in the jar on the root. Remmember to add the path with the /

One thought on “How to read a file from the JAR?

  1. If you are using spring i would use

    import org.springframework.util.ResourceUtils;

    File file = ResourceUtils.getFile(“classpath:txtData/states.properties”);

    hope this helps

Leave a Reply

Your email address will not be published. Required fields are marked *