Search code examples
javafilepdfpathapache-commons

With a Collection of File, get a getPath() relate to specific folder


i'm using

org.apache.commons.io.FileUtils

for get all the filed PDF contained in a specified folder (and relative subfolders)

Here a simple code

import java.io.File;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;

public class FileFilterTest
{
    public static void main(String[] args)
    {
        File ROOT_DIR = new File("C:\\PDF_Folder");

        Collection<File> PDF_FILES = FileUtils.listFiles(ROOT_DIR, new IOFileFilter() {

            @Override
            public boolean accept(File file)
            {
                return file.getName().endsWith(".pdf");
            }

            @Override
            public boolean accept(File dir, String name)
            {
                return name.endsWith(".pdf");
            }
        }, TrueFileFilter.INSTANCE);

        for(File pdf : PDF_FILES)
        {
            System.out.println(pdf.getPath());
        }
    }
}

the getPath() method returns the Absolute Path like this

C:\PDF_Folder\SomeFolder\AnotherFolder\A\20120430_TT006059__0000039.pdf
C:\PDF_Folder\Folder1\A\20120430_TT006060__000003A.pdf
C:\PDF_Folder\Folder1\Folder2\Folder3\B\20120430_TT006071__000003B.pdf
C:\PDF_Folder\Folder4\20120430_TT006125__000003C.pdf

Is there a way to get only the path related to the provided Root Folder?

SomeFolder\AnotherFolder\A\20120430_TT006059__0000039.pdf
Folder1\A\20120430_TT006060__000003A.pdf
Folder1\Folder2\Folder3\B\20120430_TT006071__000003B.pdf
Folder4\20120430_TT006125__000003C.pdf

EDIT: Here the solution created by code of jsn

for(File pdf : PDF_FILES)
{
    URI rootURI = ROOT_DIR.toURI();
    URI fileURI = pdf.toURI();

    URI relativeURI = rootURI.relativize(fileURI);
    String relativePath = relativeURI.getPath();

    System.out.println(relativePath);
}

Solution

  • Something like this maybe:

    String relPath = new File(".").toURI().relativize(pdf.toURI()).getPath();
    System.out.println(relPath);
    

    Tested, this works.