我尝试用Maven项目创建一个jar文件,但是当我运行jar文件时,我有一个IOException.pom.xml文件中是否要添加一些内容? 我使用Maven项目,因为我必须添加jfreechart依赖项。
这是IOException:
java.io.FileNotFoundException: src\main\resources\images\NoAHMhkB6eE.png (Le che
min d?accès spécifié est introuvable)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstan
ce(Unknown Source)
at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at l2j1.Image.createGrayscaleImage(Image.java:69)
错误代码示例:
public static Image createGrayscaleImage(String imgPath) throws IOException, NotAPictureException {
String grayscaleImagePath = null ;
BufferedImage image = null ;
File o = new File(imgPath);
if (ImageIO.read(o) == null) {
throw new NotAPictureException(o.getAbsolutePath());
}else {
image = (ImageIO.read(o));
}
BufferedImage grayscaleImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < image.getWidth() ; i++) {
for(int j = 0; j < image.getHeight(); j++) {
Color c = new Color(image.getRGB(i, j));
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int gray = (r + g + b)/3;
Color gColor = new Color(gray, gray, gray);
grayscaleImage.setRGB(i, j, gColor.getRGB());
}
}
grayscaleImagePath ="src"+File.separator+"main"+File.separator+ "resources" + File.separator + "images" + File.separator + getImgName(imgPath);
ImageIO.write(grayscaleImage, "png", new File(grayscaleImagePath));
return new Image(grayscaleImagePath, imgPath);
}
我尝试创建一个InputStream,例如:
InputStream in = Image.class.getClassLoader().getResourceAsStream("src"+File.separator+"main"+File.separator+ "resources" + File.separator + "images" + File.separator + getImgName(imgPath));
grayscaleImagePath ="src"+File.separator+"main"+File.separator+ "resources" + File.separator + "images" + File.separator + getImgName(imgPath);
byte[] buffer = new byte[in.available()];
in.read(buffer);
File targetFile = new File("src/main/resources"+File.separator + getImgName(imgPath));
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
ImageIO.write(grayscaleImage, "png", targetFile);
return new Image(grayscaleImagePath, imgPath);
但是我在缓冲区数组上有一个NullPointerException。
谢谢
答案 0 :(得分:0)
根据您发布的代码,您正在尝试将图像文件保存在此文件夹下...
src\main\resources\images\
这是相对路径。它相对于Java System
属性 user.dir 的值。在 Eclipse 中运行代码与运行JAR时,似乎该属性的值不同。
在从 Eclipse 和JAR运行时,请使用绝对路径或确保 user.dir 指向相同的位置。
当然,如果保存的文件的实际位置不重要,则也可以使用不变的System
属性“ java.io.tmpdir”或“ user.home”的值。