core-java icon indicating copy to clipboard operation
core-java copied to clipboard

Reading file exception

Open Ziegeraze opened this issue 2 years ago • 0 comments

Reading the File works when app is executed from the IDE, but if you compile and execute:

javac Main.java
java Main

then it throws:

Exception in thread "main" java.lang.IllegalArgumentException: File: app.log not found.
	at ResourceHelper.getAbsoluteFilePath(ResourceHelper.java:11)
	at Main.main(Main.java:15)

ResourceHelper.java:

public class ResourceHelper {

    public static String getAbsoluteFilePath(String filename) {
        URL resource = ClassLoader.getSystemClassLoader().getResource(filename);
        if (resource == null) {
            throw new IllegalArgumentException("File: " + filename + " not found.");
        }

        try {
            Path path = Paths.get(resource.toURI());
            return path.toString();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

}

Any suggestion to solve this?

Ziegeraze avatar Sep 09 '23 18:09 Ziegeraze