You cannot assume that resources in general are their own discrete file on the real filesystem, it is abstracted away by the classloader. If you can help it, just don't try to make this conversion. For instance, to read an image resource agnostically:
BufferedImage img;
try (InputStream in = ReadFile.class.getResourceAsStream("image.png")) {
img = ImageIO.read(in);
}
However, if for some reason you truly need to do this, you can try a hack like this:
static File resourceUrlToFile(URL url) {
if (url == null || !"file".equals(url.getProtocol()))
throw new IllegalArgumentException(url + " is not a file URL");
return FileSystems.getDefault()
.getPath(url.getPath().substring(1))
.toFile();
}
Or find the resources
directory in your development environment and work from there:
static File getResourcesDirectory() {
File src;
try {
src = new File(Main.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI());
} catch (SecurityException | URISyntaxException e) {
throw new AssertionError("Failed to read code source", e);
}
// This next step assumes a Gradle build environment,
// adapt for your build script
src = new File(
src.getParentFile().getParentFile().getParentFile(),
"resources/main"
);
return src;
}
Without care, approaches like these will break when packaging.