Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java get file paths

Tags:

java

file

path

jsp

I have a jsp page which contains the code which prints all files in a given directory and their file paths. The code is

if (dir.isDirectory())
        {
            File[] dirs = dir.listFiles();
            for (File f : dirs)
            {
                if (f.isDirectory() && !f.isHidden())
                {
                    File files[] = f.listFiles();
                    for (File d : files)
                    {
                        if (d.isFile() && !d.isHidden())
                        {
                            System.out.println(d.getName()+ 
                            d.getParent() + (d.length()/1024));
                        }
                    }
                }
                if (f.isFile() && !f.isHidden())
                {
                    System.out.println(f.getName()+ 
                    f.getParent() + (f.length()/1024));
                }
            }
        }

The problem is that it prints the complete file path, which when accessed from tomcat is invalid. For example, the code spits out the following path:

/usr/local/tomcat/sites/web_tech/images/scores/blah.jpg

and I want it to only print the path up to /images ie

/images/scores/blah.jpg

I know I could just mess around with an actual string, ie splitting it or string matching, but is there an easier way to do it?

Thanks

like image 742
user283188 Avatar asked May 06 '26 05:05

user283188


1 Answers

Relying on the filesystem like that for a webapp (i.e., using absolute paths) is not good practice will make your code less portable.

You should keep your files in a resources directory and use the ClassLoader to load your files relative to the classpath. See ClassLoader.getResource() and ClassLoader.getResourceAsStream(). Another option is to use ServletContext.getResource() or ServletContext.getResourceAsStream(). You can get the ServletContext in servlets by using the inherited getServletContext() method.

like image 199
Vivin Paliath Avatar answered May 08 '26 17:05

Vivin Paliath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!