java - 无法在maven项目的a/resources文件中使用FileOutputStream写入

标签 java maven io

在 Maven 项目中,我在 /resources 文件夹下有一个 image.jpg 文件 enter image description here

当我尝试使用

检索文件时
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/

相关文章:

java - Android 文件 IO : I and O Accessing Different Files

java - 从 Android 设备获取 GMT 时区

java - 如何将函数应用于列表列表

java - Groovy 摘要身份验证

java - 为什么我不能在 jsp 中使用 core taglib?

linux - FIO 用于重复数据访问模式的灵活 IO 测试仪

混淆原始终端模式与熟终端模式?

java - 使用另一个所有数组元素过滤数组 - Java 8

maven - 激活部署服务器上安装的基于 Maven 配置文件的软件包

scala - SBT 0.12.1 下载错误的快照