2016-09-02 27 views
-1

enter image description here我怎么能写在资源文件夹中的图像Spring MVC中的项目

@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;  
    } 

我想加载图像形成我的硬盘项目folder.but我得到了 错误(系统无法找到具体的路径)。

错误是:

java.io.FileNotFoundException:资源\ IMG \ copyright.jpg(该 系统不能找到指定的路径)

+0

运行应用程序中没有src文件夹 – Jens

回答

1

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

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

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中使用了错误的括号,因此使用内置功能更容易。

相关问题