0

I know it seems like my question has been answered before, but I can't find an answer for my case.

What I am trying to do, is to get a File type from resource, so when it's packaged, it can be accessed. The answers I found were trying to read that file, but what I really need, is to construct a File object, because I have a third party library that is expecting that object.

Here is a the code I tried:

    String xslFilePath = new Test().getClass().getResource("/com/test/decision_template.xsl").getPath();
    System.out.println(xslFilePath);
    File xsltfile = new File(xslFilePath);
    System.out.println(xsltfile.getAbsolutePath()+", exist:"+xsltfile.exists());

I got this result:

    C:\>java -jar test.jar
    file:/C:/test.jar!/com/test/decision_template.xsl
    C:\\file:\C:\test.jar!\com\test\decision_template.xsl, exist:false
    java.io.FileNotFoundException: file:\C:\test.jar!\com\test\decision_template.xsl
    (Syntaxe du nom de fichier, de rÚpertoire ou de volume incorrecte)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at com.test.Test.main(Test.java:30)

I need a way to get that file so the .exists() return true.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Otmane MALIH
  • 41
  • 2
  • 10
  • 2
    This question already has many answers for you: http://stackoverflow.com/questions/403256/how-do-i-read-a-resource-file-from-a-java-jar-file. The most reasonable thing to do would be to not require a file, but just an `InputStream` in general. – Andrew Mao Feb 27 '13 at 19:09

1 Answers1

0

You can try the TrueZip library. It's quite good. I believe you'll need to implement your own DirectoryScanner or something.

Better yet, just knock up an implementation of your own which scans through all the jars on your classpath. Here's an example of how I've done it in one of my projects on GitHub. I think that you could easily tailor it to suit your needs.

Have fun! :)

carlspring
  • 31,231
  • 29
  • 115
  • 197