2017-06-11 7 views
1

JARに含まれているクラスパス内のディレクトリにあるファイルのリストを取得するにはどうすればよいですか?JARに含まれるクラスパス内のディレクトリにあるファイルのリストを取得するにはどうすればよいですか?

質問は、JARファイルをそのまま開いて、ディレクトリ内のディレクトリにあるファイルを検索することではありません。問題は、JARがクラスパスに含まれていたため、クラスパス内に存在したディレクトリ内のファイルをリストする方法です。オープンJARファイルは必要ありません。これが不可能な場合は、あらかじめjarのファイル名を知らなくても、それをどうやってやるべきか説明してください。

は、プロジェクトがそのリソースの構造、次のようである別のプロジェクトに依存していると言う:testFolderはクラスパスで利用可能であること、どのように私はそれの下のファイルを列挙しないことを考えると

src/main/resources/testFolder 
- fileA.txt 
- fileB.txt 

testFolderは、WARのlibフォルダ内の依存関係が存在するJARの内部に置かれます。基本となる実装を読め

+0

あなたの質問から、testFolderがJARで終わるかどうかは不明です。 – pvg

+0

@pvg、もちろんそうです。実際には、this.getClass()。getClassLoader()。getResources( "testFolder")を呼び出すと、URLインスタンス(testFolderを表す1要素のEnumerable )が返されます。含まれていなければ、そのコードはURLを返しません。 – supertonsky

+0

私は、クラスローダーが本当にそれを意図しているとは思わない(具体的には、getResourcesはそうではありません)。あなたの最善の策は、http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html – pvg

答えて

0
PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver(); 
    Resource[] resources; 
    try { 
     resources = scanner.getResources("classpath*:testFolder/**/*.*"); 
     for (int i = 0; i < resources.length; i++) { 
      log.info("resource: {}", resources[i].getFilename()); 
     } 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

が、私は以下のが見つかりました:

春の実装を見てみると
URLConnection con = rootDirResource.getURL().openConnection(); 
JarFile jarFile; 
String jarFileUrl; 
String rootEntryPath; 
boolean newJarFile = false; 

if (con instanceof JarURLConnection) { 
    // Should usually be the case for traditional JAR files. 
    JarURLConnection jarCon = (JarURLConnection) con; 
    ResourceUtils.useCachesIfNecessary(jarCon); 
    jarFile = jarCon.getJarFile(); 
    jarFileUrl = jarCon.getJarFileURL().toExternalForm(); 
    JarEntry jarEntry = jarCon.getJarEntry(); 
    rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); 
} 
else { 
    // No JarURLConnection -> need to resort to URL file parsing. 
    // We'll assume URLs of the format "jar:path!/entry", with the protocol 
    // being arbitrary as long as following the entry format. 
    // We'll also handle paths with and without leading "file:" prefix. 
    String urlFile = rootDirResource.getURL().getFile(); 
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR); 
    if (separatorIndex != -1) { 
     jarFileUrl = urlFile.substring(0, separatorIndex); 
     rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length()); 
     jarFile = getJarFile(jarFileUrl); 
    } 
    else { 
     jarFile = new JarFile(urlFile); 
     jarFileUrl = urlFile; 
     rootEntryPath = ""; 
    } 
    newJarFile = true; 
} 

、それを行うための唯一の方法は、実際には、JARファイルなどのリソースを扱うことであるようです。

関連する問題