1

I'm trying to create a new file in:

project/src/resources/image.jpg

as follows:

URL url = getClass().getResource("src/image.jpg");
File file = new File(url.getPath());

but I get error:

java.io.FileNotFoundException: file:\D:\project\dist\run560971012\project.jar!\image.jpg (The filename, directory name, or volume label syntax is incorrect)

What I'm I doing wrong?

UPDATE:

I'm trying to create a MultipartFile from it:

FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "image/jpeg", IOUtils.toByteArray(input));
Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142

2 Answers2

2

You are not passing the image data to the file!! You're trying to write an empty file in the path of the image!!

I would recommend our Apache friends FileUtils library (getting classpath as this answer):

import org.apache.commons.io.FileUtils

URL url = getClass().getResource("src/image.jpg");
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
FileUtils.copyURLToFile(url, f);

This method downloads the url, and save it to file f.

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
2

Your issue is that "image.jpg" is a resource of your project. As such, it's embedded in the JAR file. you can see it in the exception message :

file:\D:\project\dist\run560971012\project.jar!\image.jpg

You cannot open a file within a JAR file as a regular file. To read this file, you must use getResourceAsStream (as detailed in this this SO question).

Good luck

Community
  • 1
  • 1
Nicolas Riousset
  • 3,447
  • 1
  • 22
  • 25