在 Maven 项目中,我在 /resources
文件夹下有一个 image.jpg
文件
当我尝试使用
检索文件时private static File getImage(){
ClassLoader classLoader = Db.class.getClassLoader();
return new File(classLoader.getResource("image.jpg").getFile());
}
文件正确返回,但是当我尝试将此文件放入 FileOutputStream 中写入一些新数据时,它不起作用
FileOutputStream fos = new FileOutputStream(getImage());
fos.write(blobImage.getBytes(1, (int)blobImage.length()));
fos.flush(); fos.close();
我没有错误,只是无法编写任何新内容,但是如果我将 FileOutputStream 更改为此
FileOutputStream fos = new FileOutputStream( "C:\\...src\\main\\resources\\image.jpg");
它工作正常,图像更改为 blobImage
文件中的任何内容。
最佳答案
这里:
private static File getImage(){
ClassLoader classLoader = Db.class.getClassLoader();
return new File(classLoader.getResource("image.jpg").getFile());
}
您检索位于运行时类路径中的image.jpg
:target/classes
而不是src/main/resouces
。
src/main/resouces
是 Maven 构建期间而不是运行时使用的资源路径。
在process-resources
Maven阶段执行后,位于src/main/resources
中的文件/文件夹被复制到target/classes
。
因此,更改后,图像实际上已更改,但位于 target/classes
中。
请注意,打包在 jar/war 中的资源不可更改。您将遇到锁定和缓存问题。如果资源可能会更改,则这些资源应位于组件外部:文件系统对于图像来说是一个公平的选择。
关于java - 无法在maven项目的a/resources文件中使用FileOutputStream写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47892165/