Webプロジェクト src/main/resources に置いたファイルを WebPage でも、
src/test/java で書くテストクラスでも読込みたい。
個別のクラスローダーで読みたく ClassLoader.getSystemClassLoader() を使ってしまうと
読めないので、Wicket の WebApplication クラスを getしてそのクラスローダーで
Webコンテナ起動で WEB-INF/classes に配置される src/main/resources に置いたファイルを
WebPage クラスでは、以下のように読込みます。
プロジェクト src/main/resources/a.json がある。
まずは、、java.nio.file.Path
Path path
= Path.of(getApplication().getClass().getClassLoader().getResource("a.json").toURI());
でもこれは、URISyntaxException を発生させるので、、
↓yipuran-core で用意した Throwable な Supplier を使います。
https://github.com/yipuran/yipuran-core/blob/master/src/main/java/org/yipuran/function/ThrowableSupplier.java
( Java11 Files.readString も使ってます )
File file = new File(Optional.of( ThrowableSupplier.to( ()->getApplication().getClass().getClassLoader().getResource("a.json").toURI()).get() ).get()); String s = ThrowableSupplier.to(()->Files.readString(file.toPath(), Charset.forName("UTF-8")) ).get();
もっと短く書けるはずで、絶対に存在するファイルなら、以下のように書けます。
String s = ThrowableSupplier.to(()->Files.readString( Path.of(getApplication().getClass().getClassLoader().getResource("a.json").toURI()) , Charset.forName("UTF-8")) ).get();
それでも、ThrowableSupplier は、
static <R> Supplier<R> to(ThrowableSupplier<? extends R> supplier, Function<Exception, R> onCatch)
であるので、
String s = ThrowableSupplier.to(()->Files.readString( Path.of(getApplication().getClass().getClassLoader().getResource("a.json").toURI()) , Charset.forName("UTF-8")) , x->{ // ファイル読込み失敗時の処理をする return "file read error"; }).get();
とも書けます。
src/test/ の方で記述するコード
Wicket の WebApplication 継承クラスが、MyApplication だとして、、
String s = ThrowableSupplier.to(()->Files.readString( Path.of(MyApplication.class.getClassLoader().getResource("a.json").toURI()) , Charset.forName("UTF-8")) , x->{ return "Not Found file"; }).get();
テスト用とWeb実装用、同じ src/main/resources に置いたファイルを読み込めます。