Java:inputStream = null来自资源中的pdf文件

时间:2016-08-02 08:31:29

标签: java tomcat pdf

我尝试打开pdf文件并将其显示在客户端的桌面上。 我在Tomcat服务器上使用java。 该文件位于项目的resources文件夹中,构建完成后位于WEB-INF / resources / in.pdf

inputStream返回null,我怎样才能找到文件的真实路径?

这是代码:

    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();
    }

1 个答案:

答案 0 :(得分:0)

现在getResourceAsStream引用类路径上的资源,文件,可能包装在jar或war中。

然后WEB-INF又是一个webserver目录,路径不是WEB-INF / classes之类的东西。因此,您必须位于servlet中,并检索Web目录/ 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());
        }

然后,当前桌面应再次显示PDF(同一台计算机上的网络服务器和桌面)。

如果服务器是远程计算机,除了某些元信息文件外,WEB-INF通常应该是不可访问的。