0

I'm trying to retrieve all the files inside a resources folder to be able to use it on JAXB unmarshaller, but i could'nt find anything that i could use instead of the regular file.listFiles() on java.

I've tried File files = new File(this.context.getResource("/WEB-INF/folder").getPath()); and use it on a foreach loop, but a null pointer was thrown.

Just to point it out, context is a Jersey @Context ServletContext context injected variable.

@Update

Ok, im using getResourcePaths now and converting each path to uri and than to file.

Set<String> catalogosPath = this.context.getResourcePaths("/WEB-INF/catalogos/");
        for(String catalogoPath : catalogosPath){
            URI uri = context.getResource(catalogoPath).toURI();
            File arquivo = new File(uri.getPath());
            tempCat = (Catalogo) jaxbUnmarshaller.unmarshal(arquivo);
            catalogos.add(tempCat);
        }

Than tomcat is throwing me an error, it says that the file /localhost/cvrest/WEB-INF/catalogos/myfile.xml Doesnt exist but it exist. I'm trying to unmarshall it but it keeps me throwing no file found. I might be missunderstanding the return from getresourcepaths, it gives me an url, am i converting it right?

GoldenMedal
  • 102
  • 2
  • 9
  • Whatever answer you get, NEVER use `getRealPath()`, just use `getResourcePaths()`. See also http://stackoverflow.com/q/12160639 – BalusC May 27 '16 at 11:00
  • @BalusC I wasn't aware of that. I've updated my answer to use `getResource()`. – cassiomolin May 27 '16 at 11:16
  • @Cássio: you're still treating them as local disk file system paths. As said, use `getResourcePaths()` and do in no way convert them to `File`/`Path`. It are not per definition files. Those can reside in memory or virtual file system or even somewhere else in network (in other words, URI doesn't guaranteed start with `file://`) – BalusC May 27 '16 at 11:35
  • @BalusC Makes sense. – cassiomolin May 27 '16 at 11:38
  • @BalusC i've updated the question. – GoldenMedal May 27 '16 at 21:44
  • You should not be attempting to interpret them as local disk file system paths. Just use `getResourceAsStream()`. – BalusC May 28 '16 at 06:09

1 Answers1

-1

You can use context.getRealPath("/") inside your servlet to get the base path of your project. To get the list of files just append your file path relative to your project path, for example, context.getRealPath("/") + "/WEB-INF/classes/folder

imran arshad
  • 274
  • 1
  • 12