java - URL.openStream 抛出错误

标签 java spring url

请帮我解决这个问题,我正在尝试编写一段代码来使用 Apache FOP 生成 PDF。我开发了 XSL-FO,它位于应用程序的资源文件夹中,即 src/main/resource。 现在,当我通过 Junit 进行测试时,它工作正常,但是当我从应用程序中尝试时,我遇到了问题。

java.io.FileNotFoundException: C:\Users\abc\development\Eclipse\eclipse\file:\C:\Users\abc\development\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\dmu-portal-ui\WEB-INF\lib\XYZservices-1.0.7-SNAPSHOT.jar!\XSLtemplate\templateSummary.xsl (The filename, directory name or volume label syntax is incorrect)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:101)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at java.net.URL.openStream(URL.java:1037)

代码

public String createPDFFile(ByteArrayOutputStream xmlSource, String templateFile) throws IOException {
        File file = File.createTempFile("caseSummary-" + System.currentTimeMillis(), EXTENSION);
        URL url = new File(this.getClass().getResource("/" + templateFile).getPath()).toURI().toURL();
        //URL url = new File(templateFile).toURI().toURL();
        //URL url = new URL(templateFile);
        // creation of transform source
        //StreamSource transformSource = new StreamSource(getClass().getResourceAsStream("/" + templateFile));
        StreamSource transformSource = new StreamSource(url.openStream());
        // create an instance of fop factory
        FopFactory fopFactory = FopFactory.newInstance();
        // a user agent is needed for transformation
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        // to store output
        ByteArrayOutputStream pdfoutStream = new ByteArrayOutputStream();
        StreamSource source = new StreamSource(new ByteArrayInputStream(xmlSource.toByteArray()));
        Transformer xslfoTransformer;
        try {
            TransformerFactory transfact = TransformerFactory.newInstance();

            xslfoTransformer = transfact.newTransformer(transformSource);
            // Construct fop with desired output format
            Fop fop;
            try {
                fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, pdfoutStream);
                // Resulting SAX events (the generated FO)
                // must be piped through to FOP
                Result res = new SAXResult(fop.getDefaultHandler());
                // Start XSLT transformation and FOP processing
                try {
                    // everything will happen here..
                    xslfoTransformer.transform(source, res);
                    // if you want to save PDF file use the following code
                    OutputStream out = new java.io.FileOutputStream(file);
                    out = new java.io.BufferedOutputStream(out);
                    FileOutputStream str = new FileOutputStream(file);
                    str.write(pdfoutStream.toByteArray());
                    str.close();
                    out.close();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            } catch (FOPException e) {
                e.printStackTrace();
            }
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            e.printStackTrace();
        }
        return file.getPath();
    }

我发现问题 在 url.openStream 中,当尝试从应用程序中使用时,路径是重复的,但是当从 Junit 访问时,它运行良好。

技术栈 JDK:1.7 Spring :4.1.5

请帮我解决问题

最佳答案

首先,正如 JB Nizet 所说,您不应使用 URL 或文件来读取模板。你不需要其中任何一个;您只需要从 InputStream 读取打包的资源即可:

try (InputStream xslStream = getClass().getResourceAsStream("/" + templateFile)) {
    StreamSource transformSource = new StreamSource(xslStream);

其次,Class.getResource 和 Class.getResourceAsStream 方法(及其 ClassLoader 等效方法)需要 a String argument containing forward slashes (/) ,在所有平台上,甚至 Windows。

因此,要么更改调用代码,使其传递 "XSLTemplate/summary.xsl",要么在方法的开头放置类似的内容:

templateFile = templateFile.replace('\\', '/');

关于java - URL.openStream 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29374240/

相关文章:

java - 尝试在 hibernate/spring 中创建用户登录的东西

django - 抓取request.GET中的URL参数

java - launch4j和classpath上的外部文件

java - 从 java.util.function.Function 获取方法名称

java - 如何获取信号量以通知该信号量上的等待线程? ( java )

java - 带有json的Spring rest junit帖子

java - (如何)我可以让 JAXB (MOXy) 接受非 setter/getter 进行编码?

java - 泽西 + Spring + hibernate

jquery - 从当前 url 添加/删除 anchor 名称而不刷新

c# - 如何通过 FormUrlEncodedContent 传递 List<int>