我正在使用
org.apache.commons.io.FileUtils
获取包含在指定文件夹(和相关子文件夹)中的所有归档 PDF
这里有一个简单的代码
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());
}
}
}
getPath() 方法像这样返回绝对路径
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
有没有办法只获取与提供的根文件夹相关的路径?
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
编辑:这里是由 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);
}