Last active
April 13, 2024 07:55
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.