如何在jar文件中获取资源? (poi&& image)

时间:2013-07-23 23:19:13

标签: jar apache-poi

我正在使用Poi Apache生成一个excel文件,我必须在我的文件中添加一张图片,但问题是当我将项目导出到Runnable Jar时,它无法正常工作。

InputStream is = ExcelTools.class.getClassLoader().getResourceAsStream( "./ensao/pfa/opendelib/resources/LogoOpen.jpg" );

    byte[] bytes = IOUtils.toByteArray(is);
    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
    is.close();

    Drawing drawing = sheet.createDrawingPatriarch();
    HSSFClientAnchor anchor = new HSSFClientAnchor(40, 10, 65, 20,
            (short) 0, 0, (short) 0, 0);
    anchor.setAnchorType(1);

    Picture pict = drawing.createPicture(anchor, pictureIdx);
    pict.resize();

问题是从这一行开始的:

byte[] bytes = IOUtils.toByteArray(is);

1 个答案:

答案 0 :(得分:1)

图像路径不好的问题。您的IDE配置环境($ CLASSPATH,文件路径等)以一种方式,但实际运行操作其他环境。要找到您的工作目录,请打印debug pwd analog。

此链接可能有用: http://www.java-forums.org/new-java/434-how-can-i-get-current-directory.html http://www.mkyong.com/java/how-to-get-the-current-working-directory-in-java/ Getting the Current Working Directory in Java