2016-10-12 118 views
2

パス定義でワイルドカードを使用できるかどうか、またその使用方法を知りたい。 私は1つのフォルダを深くしたいと思って*を使って試しましたが、それはうまくいきません。Javaファイルパスでのワイルドカードの使用方法

ランダムなフォルダにあるファイルにアクセスしたいと思います。 Folderstructureはこのようなものです:私が試した

\test\orig\test_1\randomfoldername\test.zip 
\test\orig\test_2\randomfoldername\test.zip 
\test\orig\test_3\randomfoldername\test.zip 

何:

File input = new File(origin + folderNames.get(i) + "/*/test.zip"); 

File input = new File(origin + folderNames.get(i) + "/.../test.zip"); 

は、事前にありがとうございます!

+1

あなたはより深い1つのフォルダを何を意味するか、あなたが行きたいフォルダいる指定する必要があります。 –

+0

試しましたか?http://stackoverflow.com/questions/30088245/java-7-nio-list-directory-with-wildcard – kjsebastian

+0

明快に試して編集します – Warweedy

答えて

0

このようにワイルドカードを使用することはできません。 Path pathとラムダ式が全体と一致するPath.endsWith使用するファイルに、

File orig = new File("\test\orig"); 
    File[] directories = orig.listFiles(new FileFilter() { 
     public boolean accept(File pathname) { 
     return pathname.isDirectory(); 
     } 
    }); 
    ArrayList<File> files = new ArrayList<File>(); 
    for (File directory : directories) { 
     File file = new File(directory, "test.zip"); 
     if (file.exists()) 
      files.add(file); 
    } 
    System.out.println(files.toString()); 
+0

おかげでトリックがやった! – Warweedy

1

使用新しいパス、パス

Files.find(Paths.get("/test/orig"), 16, 
      (path, attr) -> path.endsWith("data.txt")) 
     .forEach(System.out::println); 

    List<Path> paths = Files.find(Paths.get("/test/orig"), 16, 
      (path, attr) -> path.endsWith("data.txt")) 
     .collect(Collectors.toList()); 

注:私はあなたがあなたの仕事のために、このような方法を使用することを提案しますtest1/test.zipまたはtest.zipのような名前です。

ここには、参照するディレクトリツリーの最大の深さがあります。 varargsオプションパラメータがあります。たとえば、(ない)他のディレクトリへのシンボリックリンクをたどります。

その他の条件は、次のようになります。

path.getFileName().endsWith(".txt") 
path.getFileName().matches(".*-2016.*\\.txt") 
0

あなたはPathMatcherを使用してwildcardardを使用することができます。

あなたのPathMatcherのために、このようなパターンを使用することができます。

/* Find test.zip in any subfolder inside 'origin + folderNames.get(i)' 
* If origin + folderNames.get(i) is \test\orig\test_1 
* The pattern will match: 
* \test\orig\test_1\randomfolder\test.zip  
* But won't match (Use ** instead of * to match these Paths): 
* \test\orig\test_1\randomfolder\anotherRandomFolder\test.zip 
* \test\orig\test_1\test.zip 
*/ 
String pattern = origin + folderNames.get(i) + "/*/test.zip"; 

ありますFileSysten.getPathMatherメソッドのこのパターンの構文に関する詳細。 PathMatherを作成するコードは次のようになります。

PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); 

あなたはFiles.find()メソッドを使用してこのパターンに一致するすべてのファイルを見つけることができます:

Stream<Path> paths = Files.find(basePath, Integer.MAX_VALUE, (path, f)->pathMatcher.matches(path)); 

findメソッドはStream<Path>を返します。そのストリームに対して操作を実行したり、リストに変換することができます。

paths.forEach(...); 

または:

List<Path> pathsList = paths.collect(Collectors.toList()); 
関連する問題