1

I have a bit problem, and i dont seem to understand what is causing it. i have a folder in my project, and in that folder i have a class, and i have a resource file (in this case jasper report). but the only way i can access file is with absolute path or some path that starts from root of my project.

String path = "src/main/java/Views/LagerMain/lager.jrxml";

^^this works, both my class LagerController and lager.jrxml are under LagerMain folder, but when i try to do this :

String path = "lager.jrxml";

i have an error that file is not found. I tried googling this to have a better understanding but i found nothing.

Bottom line, why cant i access my file, from class when they are both on same place, why does not relative path work.

0

1 Answer 1

1

If the main class is in a different directory, then the program will try to accesslager.jrxml there instead of the directory of the regular class.

For regular-class directory:

String path = new String(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.getPath() + System.getProperty("line.separator") + "lager.jrxml");

If that doesn't work, try this:

// your directory
File f = new File("src");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("lager") && name.endsWith("jrxml");
    }
});

If you have more than one file with the name lager.jrxml, then this method will return both of them and you will need to use a for to cycle through them. Otherwise, you can just use

String path = new String(matchingFiles[0].getAbsolutePath())

For main-class directory:

String path = new String(System.getProperty("user.dir")
 + System.getProperty("line.separator") + "lager.jrxml");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.