[英]Java search files from folder
我正在編寫一個實用程序,它將搜索文件夾並列出文件。 主要目的是查找所有具有相同名稱但具有diff擴展名的文件。 例如:在給定的文件夾中,我們有a.log,a.jpg,a.clone,b.log,c.log,d.log,d.clone的文件,我的輸出應僅為c.log和d .log。 我的主要目的是查找包含.clone擴展名的文件,並且在這種情況下不打印它們,而文件c和d不具有.clone擴展名,它們應該是輸出。 我無法列出名稱相同但擴展名不同的文件。
關於如何進行此操作的任何建議。
問候,維拉斯
當您列出某個文件夾中的所有文件時,例如: File[] files = file.listFiles()
,可以循環瀏覽它們並檢查文件名。 在這里, file
實際上是您要在其中搜索文件的文件夾。
for(int i=0; i<files.length; i++)
{
if(files[i].getName().startsWith("filename."))
{
do what you want
}
}
因此,所有以"filename."
開頭的"filename."
不管之后發生什么,都將符合條件.
即擴展。
從Java 7開始,您可以使用walkTreeFile()
來控制要深入樹的深度以及如何處理找到的每個文件(使用適當的FileVisitor
)。
使用Executor
您可以處理文件,而無需等待搜索完成。
從Java 8開始,您不應像以前建議的那樣使用FileVisitor
, walkTreeFile()
和File
類,而應使用Path
接口和Files.list(Path dir)
:
public static void main(String[] args) throws IOException
{
Path folderWithTheFiles = Paths.get("/my/folder/with/the/files/");
//list the folder and add files names with a .clone extension in a Set
Set<String> cloneFilesNames = Files.list(folderWithTheFiles)
.filter(p->p.toString().endsWith(".clone"))
.map(p -> p.getFileName().toString().split("\\.")[0]).collect(Collectors.toSet());
//list the folder and filter it with the Set created before
Files.list(folderWithTheFiles)
.filter(p->!cloneFilesNames.contains(p.getFileName().toString().split("\\.")[0]))
.map(Path::getFileName).forEach(System.out::println);
}
如果要在文件樹中進行更深入的搜索,請使用Files.walk(Path dir)
而不是Files.list(Path dir)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.