项目在Eclipse中工作,但打包在罐子中后无法工作 [英] Project works in eclipse but not after being packaged in a jar
问题描述
我的项目使用itext7创建PDF文件.当我从eclipse启动时,一切运行正常.当我将其包装为罐子时,一切正常,直到我要创建PDF为止.然后我得到:
My project uses itext7 to create PDF files. When I launch from eclipse everything works perfectly. When I package it as a jar, everything works until I get to the point that I want to create a PDF. I then get:
线程"JavaFX Application Thread"中的异常com.itextpdf.io.IOException:I/O异常.
.....
Exception in thread "JavaFX Application Thread" com.itextpdf.io.IOException: I/O exception.
.....
原因:java.io.FileNotFoundException:C:\ Users \ puser \ eclipse-workspace \ Document \ target \ SE001-0.1.1-SNAPSHOT.jar \ img \ Safety.png(系统找不到指定的路径)
Caused by: java.io.FileNotFoundException: C:\Users\puser\eclipse-workspace\Document\target\SE001-0.1.1-SNAPSHOT.jar\img\Safety.png (The system cannot find the path specified)
项目文件夹将图像保存在src/main/resources/img
.一旦创建了jar,它的根目录就简单地带有/img
.这意味着您不能仅指定直接路径,因为它会在创建jar时发生变化. JavaFX Images可以正常使用.
The project folder keeps the images at src/main/resources/img
. Once the jar is created it simply has /img
at root. This means you can't just specify a direct path because it changes when the jar is made. JavaFX Images work fine with..
Image user = new Image(getClass().getResourceAsStream("/img/Document.png"));
将它与itext7一起使用不起作用,因为ImageDataFactory.create()
正在寻找byte [],并且这是输入流.
Using that with itext7 doesn't work because ImageDataFactory.create()
is looking for byte[] and that is an input stream.
现在尝试使用:
Image safetyImage = new Image(ImageDataFactory.create(System.getProperty("user.dir") + "/img/Safety.png"));
不起作用,因为Jar不在路径内.
Does not work because the Jar is not inside the path.
我可以用来指向jar中的图像文件并将其与ext7一起使用吗?
What can I use to point to an image file inside the jar and use it with it ext7?
推荐答案
mkl是正确的,谢谢!
mkl was correct and thank you!
我创建了一个实用程序方法来将输入流转换为字节数组.
I created a utility method to convert an input steam to a byte array.
public static byte[] toByteArray(InputStream in) throws IOException {
//InputStream is = new BufferedInputStream(System.in);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
int len;
// read bytes from the input stream and store them in buffer
while ((len = in.read(buffer)) != -1) {
// write bytes from the buffer into output stream
os.write(buffer, 0, len);
}
return os.toByteArray();
}
然后我在ImageDataFactory.create()方法中使用了该实用程序.
I then used that utility inside the ImageDataFactory.create() method.
Image safetyImage = new Image(ImageDataFactory.create(toByteArray(getClass().getResourceAsStream("/img/Safety.png"))));
这篇关于项目在Eclipse中工作,但打包在罐子中后无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!