Josh Desmond
Josh Desmond

Reputation: 690

How to retrieve the absolute path of a file stored inside the jar

I have a file, ("hwc.bat") stored inside of my projects resources folder: "project/res/HWC/hwc.bat".

I am writing code from within a class "/src/test/java/.../aTest.java"

I want to be able to retrieve the absolute path of the file hwc.bat, but using getResource isn't working for me. Here's what I've been trying:

final URL resource = this.getClass().getClassLoader().getResource("hwc.bat");
absolutePath = Paths.get(resource.toURI()).toString();

I've tried plenty of variations of "hwc.bat", including things like "/hwc.bat", or "/res/HWC/hwc.bat", but I can't seem to get the URL to be anything but null.

Here is a picture of my project set-up, just to give a better idea of where the file is and what I'm trying to do/the context of everything.

Image of Class Layout

Upvotes: 1

Views: 4524

Answers (2)

JAVAC
JAVAC

Reputation: 1270

you are using maven structure, so you have to place resource files in src/main/resources

Upvotes: 1

wero
wero

Reputation: 32980

ClassLoader().getResource only can find resource which are contained in the classpath. This not the case for the current location of your hwc.bat.

Since you are using a Maven project, the correct location to place the file is in src/main/resources in order to find it via ClassLoader.getResource("hwc.bat").

Upvotes: 3

Related Questions