0

I try to open a pdf file and display it on the client's desktop. I use java on a Tomcat server. The file is in the resources folder of the project, and after the build is in WEB-INF/resources/in.pdf

The inputStream returns null, how can i found the real path of the file?

here is the code:

    try{
        if (Desktop.isDesktopSupported()) {
            File file = new File("out.pdf");
            if (!file.exists()) {
                InputStream inputStream = ClassLoader.getSystemClassLoader()
                        .getResourceAsStream("/WEB-INF/resources/in.pdf");
                OutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.close();
                inputStream.close();
            }
            Desktop.getDesktop().open(file);
        }
    }catch(Exception e1)
    {
        e1.printStackTrace();
    }
Marc El Bichon
  • 387
  • 1
  • 6
  • 21
  • 1
    http://stackoverflow.com/questions/1108434/howto-load-a-resource-from-web-inf-directory-of-a-web-archive ... try `getResourceAsStream("WEB-INF/resources/in.pdf")` – Tom Aug 02 '16 at 08:36

1 Answers1

0

Now getResourceAsStream refers to resources, files on the class path, possibly packed in a jar or war.

Then again WEB-INF is a webserver directory, and the path is not WEB-INF/classes or something. So you must be in a servlet, and retrieve the file system path to the web directory /WEB-INF

        File file = new File("out.pdf");
        if (!file.exists()) {
            File source = request.getServletContext()
                    .getRealPath("/WEB-INF/resources/in.pdf");
            Files.copy(source.toPath(), file.toPath());
        }

Then again the current desktop should show the PDF (webserver and desktop on the same computer).

Should the server be a remote machine, WEB-INF in general should be inaccessible except for some meta-information files.

Joop Eggen
  • 96,344
  • 7
  • 73
  • 121