jarの中からtxtファイルのリストをつくりたい 2012/12/07

Javaです。 jarのパッケージの中にtxtファイルを格納して実行中に一覧を取得したいなーというわけです。

参考にしたサイト


格納されているパッケージのクラスの位置からgetResource(".")して、返った値がnullならjarで実行中という判断をして、getProtectionDomain().getCodeSource()して、getLocation()して、それからZipInputStreamしてjarからエントリーをとりだして、ひとつづつ調べているわけです。このエントリーは平にとれちゃうので、jarの中のルートの位置からとりださないととりづらいので、classLoaderからgetResource()して、パスを取得というふうなコードにしています。
下記参考コード

URL url = Main.class.getResource("."); if (url == null) { CodeSource source = Main.class.getProtectionDomain() .getCodeSource(); if (source != null) { ClassLoader loader = Main.class.getClassLoader(); URL jar = source.getLocation(); ZipInputStream zip = new ZipInputStream( jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String entryName = ze.getName(); if (entryName.endsWith(".txt")) { System.out.println(entryName); System.out.println(loader .getResource(entryName) .toExternalForm()); } } } return; }

: