Java 使用文件集合,获取与特定文件夹相关的getPath()
我正在使用Java 使用文件集合,获取与特定文件夹相关的getPath(),java,file,pdf,path,apache-commons,Java,File,Pdf,Path,Apache Commons,我正在使用 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
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());
}
}
}
是否有办法仅获取与提供的根文件夹相关的路径
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);
}
可能是这样的:
String relPath = new File(".").toURI().relativize(pdf.toURI()).getPath();
System.out.println(relPath);
经过测试,这是可行的。一种方法是从文件名中简单地“减去”根路径:
pdf.getPath().substring(ROOT_DIR.getPath().length() + 1)
你也可以这样做:
for(File pdf : PDF_FILES)
{
System.out.println(pdf.getParentFile().getName()
+ System.getProperty("file.separator")
+ pdf.getName());
}
我确实犯了错误,但我忘了澄清一下,没有定义要搜索的子目录的数量。路径可能彼此有很大的不同(为了更好地解释,我编辑了主要帖子)。getParentFile().getName()方法只提供最后一个文件夹name@DevilingMaster:在这种情况下,Reimeus的答案就是你想要的:)@Sujay:我会使用jsn解决方案,它正在工作(我已经在主帖子中添加了最终代码)@DevlingMaster实际上,那里有重复的代码,我编辑了。我已经根据你的提示在主要问题中添加了我的最终代码。谢谢
for(File pdf : PDF_FILES)
{
System.out.println(pdf.getParentFile().getName()
+ System.getProperty("file.separator")
+ pdf.getName());
}