如何在spring mvc项目的resources文件夹中写入图像

时间:2016-09-02 20:01:18

标签: java eclipse spring spring-mvc bufferedimage

enter image description here

@GET
    @Path("/welcome1")
    @Produces(MediaType.APPLICATION_JSON)
    public Response image() {
        try {
            BufferedImage originalImage = ImageIO.read(new File("F:\\images\\1.jpg"));
            ImageIO.write(originalImage, "jpg", new File("resources\img\copyright.jpg"));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }    
        return null;    
    }
  

我想将图像从我的磁盘加载到项目文件夹。但我得到了   错误(系统找不到特定路径)。

     

错误是:

     
    

java.io.FileNotFoundException:resources \ img \ copyright.jpg(The     系统找不到指定的路径)

  

2 个答案:

答案 0 :(得分:1)

File表示文件系统中的文件,而不是类路径中的文件。类路径包含类和资源所在的位置。通常将类和资源复制到应用程序运行时的某个位置,例如复制到jar文件或目录中。

您的代码在考虑您的类路径时做出了不同寻常的假设,它依赖于当前的工作目录。我建议将文件写入文件系统,因为您没有提到应用程序需要修改自己。

答案 1 :(得分:0)

为了将来参考,如果您包含目录结构的示例,将会很有帮助。

通常,只有父目录存在时,Java才会创建不存在的文件。您应该检查/创建目录树,然后检查文件。

您还需要构建自己的路径。

    //User directory - can also use System.getProperty("user.dir")
    String path = new File("").getAbsolutePath();
    String filename = "abc.txt";
    File f = new File(path + File.separator + "resources" + File.separator + "org" + File.separator + "project" + File.separator + "playground" + File.separator + filename);
    //You should also check to make sure that the directory exists. I didn't do that here.
    if (f.createNewFile()) {
        System.out.println("File is created!");
    } else {
        System.out.println("File already exists.");
    }

请注意我没有使用\/,因为这些完全依赖于系统。 (Windows / Unix),顺便说一句,如果你使用的是Windows,那么你在java中使用了错误的括号,所以使用内置功能会更容易。

相关问题