0

I am having a web application having following structure:

WEB-INF
 |-classes
     |-templates
         |-abc.properties
         |- xyz.properties
 |-lib
     |-internal.jar (all classes of our application)
     |- other jars

These are bundled as a war

I want to get name of the files present in WEB-INF/classes/templates Also I want to get the file object of a file in WEB-INF/classes/templates based on name of the file. NOTE: Above operation needs to be done from one of the class present in internal.jar. Basically they are on classpath

Pratham
  • 61
  • 1
  • 7

1 Answers1

2

I want to get the file object of a file in WEB-INF/classes/templates based on name of the file

With java.io.File, you can't do that.

With the java.nio.file API, you can:

final Path warpath = Paths.get("path to your war file here");

final URI uri = URI.create("jar:" + warpath.toUri());

try (
    final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
) {
    final Path templates = zipfs.getPath("/WEB-INF/classes/templates");
    // walk "templates" with Files.walkFileTree()
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • We need more recommendations for the `java.nio.file` API. Too many old tutorials neglect it. +1 – Rudi Kershaw Dec 17 '14 at 14:44
  • @fge, actually I want to access these files from one of the class in internal.jar which is present in WEB-INF/lib. Basically i dont know the path of war – Pratham Dec 17 '14 at 14:52
  • @Pratham this is unclear; is that on a live, running environment? – fge Dec 17 '14 at 14:53
  • @fge, yes, these are template files using which we want to create new files which will be saved in some other location on the user disk – Pratham Dec 17 '14 at 14:56
  • So, this is a running application, then? Which means the templates you want are in the classpath? – fge Dec 17 '14 at 15:27
  • @fge yes, they are in classpath – Pratham Dec 21 '14 at 16:50
  • Then use `ClassLoader#getResource()`; but really you should specify your problem a little more. These are classpath resources, therefore you should ALWAYS rely on the classloader, and NEVER use other means to access to resources than .getResource*() – fge Dec 21 '14 at 17:02