Java get file paths

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

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 full path to the file, which is invalid when accessing from tomcat. For example, the code displays the following path:

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

and I want it to print only the path to / images, i.e.

/images/scores/blah.jpg

I know that I could just mess around with a real string, i.e. split it or match strings, but is there an easier way to do this?

thank

+3
source share
3 answers

You need to fine tune the root path.

File root = new File(getServletContext().getRealPath("/"));
for (File file : root.listFiles()) {
    // ...
    String path = file.getAbsolutePath().substring(root.getAbsolutePath().length());

, System.out.println() . , IDE . , JSP . Java JSP .

+2

Since it /usr/local/tomcat/sites/web_tech/images/scoresis the specified directory, having /usr/local/tomcat/sites/web_techroot as the output seems a bit ... arbitrary.

The best I can think of is to have File root = <your intended root>;and then do something similar to

String path = f.getName();
while (!f.equals(root)) {
    f = f.getParent();
    path = f + "/" + path;
}
0
source

Source: https://habr.com/ru/post/1742537/


All Articles