Skip to content

Instantly share code, notes, and snippets.

@adideas
Last active April 13, 2024 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adideas/0aefc526d22b5a5f3833361dab9acbff to your computer and use it in GitHub Desktop.
Save adideas/0aefc526d22b5a5f3833361dab9acbff to your computer and use it in GitHub Desktop.
Intellij Idea Resource Loader - "Resources not found in plugin" (Intelij Idea) (idea plugin) (java)! It may not be the best solution, but it works. resource loading even in unit tests.
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ResourceList;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* This work in (JUnit, Jar, etc.)
* It's better to create a new instance each time
*
* @author Aleksei Vlasov (github.com/adideas)
*/
public class IntellijIdeaResourceLoader {
String dir = null;
public IntellijIdeaResourceLoader() {
if (Thread.currentThread().getContextClassLoader() == null) {
// without jar
dir = System.getProperty("user.dir");
if (dir == null) {
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
try {
dir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());
} catch (Exception ignore) {}
}
dir = new File(dir, "resource").getAbsolutePath();
}
}
public URL getResource(Class<?> anyClassFromYouProject, String filePath) {
if (dir != null) {
try {
return new URL("file://" + new File(dir, filePath).getAbsolutePath());
} catch (Exception ignore) {}
}
URL url = null;
url = anyClassFromYouProject.getClassLoader().getResource(filePath);
if (url != null) {return url;}
Thread.currentThread().setContextClassLoader(anyClassFromYouProject.getClassLoader());
url = Thread.currentThread().getContextClassLoader().getResource(filePath);
if (url != null) {return url;}
ResourceList resources = new ClassGraph().acceptPaths(filePath).scan().getAllResources();
if (!resources.isEmpty()) {
resources.get(0).getURI();
}
return null;
}
public InputStream getResourceAsStream(Class<?> anyClassFromYouProject, String filePath) {
URL url = getResource(anyClassFromYouProject, filePath);
if (url != null) {
try {
return url.openStream();
} catch (IOException ignore) {}
}
return null;
}
}
@adideas
Copy link
Author

adideas commented Jan 4, 2023

This is an old problem, and everyone seems to solve it in their own way. I hope this helps someone.

@Jvp2001
Copy link

Jvp2001 commented Jul 1, 2023

Thank you. I just had to change line 17 to not equal; currently, I am not worried about building an actual Jar for my application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment