1

Let's say I have a package: com.example.resources and inside it I have picture.jpg and text.txt - How can I use only the package path to identify the absolute filepath of picture.jpg and text.txt?

Is this correct?

File file1 = new File("/com/example/resources/picture.jpg");
file1.getAbsolutePath();

File file2 = new File("/com/example/resources/text.txt");
file2.getAbsolutePath();
Paul Samsotha
  • 188,774
  • 31
  • 430
  • 651
ThreaT
  • 3,644
  • 13
  • 58
  • 97
  • "create 2 new File objects" Why? –  Feb 21 '14 at 10:49
  • You have to use a `ClassLoader` for that; what is more, you want `.getCanonicalPath()`. – fge Feb 21 '14 at 10:55
  • Sorry, Really i cant get you. – ashokramcse Feb 21 '14 at 10:55
  • The resources will likely be inside a jar file once the application is packaged and deployed. So there's no file path for these resources. What are you trying to achieve? – JB Nizet Feb 21 '14 at 10:59
  • Just take a look [getting-all-classes-from-a-package](http://stackoverflow.com/questions/1810614/getting-all-classes-from-a-package) what will help you. – Suzon Feb 21 '14 at 11:06

2 Answers2

1

"I'm trying to reference those files within the application so that when I deploy the application to different systems I won't have to reconfigure the location of each resource "

You don't want to use a File, which will load from the file system of the local machine, you want to load through the class path, as that's how embedded resources should be read. Use getClass().getResourceAsStream(..) for the text file and getClass().getReource(..) for the image

Your current path you're referencing looks like it should work, given the package name you've provided.

Take a look at this answer and this answer as some references.

Community
  • 1
  • 1
Paul Samsotha
  • 188,774
  • 31
  • 430
  • 651
-1

I've figured out how to do it. Here is the code that I used:

public String packagePathToAbsolutePath(String packageName, String filename) {
    String absolutePath = "File not found";
    URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
    File[] files = new File(root.getFile()).listFiles();
    for (File file : files) {
        if (file.getName().equals(filename)) {
            absolutePath = file.getName();
            return absolutePath;
        }
    }
    return absolutePath;
}

This method was really useful because it allowed me to configure the resource paths within the application so that when I ran the application on different systems I didn't have to reconfigure any paths.

ThreaT
  • 3,644
  • 13
  • 58
  • 97