nr.iras.sk
nr.iras.sk

Reputation: 8488

Create a new file in maven resource folder

this.getClass().getResource("file path")

I know this will access the file in maven's resource folder.

But how can I create a new file in maven resource folder.

Upvotes: 0

Views: 1112

Answers (2)

Martin Ellis
Martin Ellis

Reputation: 9651

If you know that the class file for the given class won't be loaded from a JAR file when its code executes, you can use something like this:

File file = new File(getClass().getResource(filename).toURI());
file.createNewFile();

This pattern can be useful in unit test code, which typically executes before any class files are packed into a jar.

Note that you may need to wrap this in a try-catch block, because the URL.toURI() method may throw a URISyntaxException. However, for test code, you might just want to add a throws clause to the method declaration.

Upvotes: 0

Καrτhικ
Καrτhικ

Reputation: 3905

You can't for the simple reason that the classpath can be mapped to a URL or a JAR file and there is no way to "create" a resource inside an already existing JAR or a remote URL.

Upvotes: 1

Related Questions