Program-Me-Rev
Program-Me-Rev

Reputation: 6624

How to create a file from classpath

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));

Upvotes: 1

Views: 5236

Answers (2)

Nicolas Riousset
Nicolas Riousset

Reputation: 3619

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

Upvotes: 2

Jordi Castilla
Jordi Castilla

Reputation: 26981

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.

Upvotes: 2

Related Questions