resources ではなく、Javaソースと同じ場所にファイルを置いて
ビルド後の classes の同じパッケージ階層に配置されたファイルを読み込む方法、
java 拡張子以外のファイルもビルドで、class と共に同じ場所に配置されるころが前提条件であるが、
以下のように、カレントスレッドのスタックトレースから場所を割り出せば
そのファイルも読める。
public File getCurrentPathFile(String path) throws IOException{ try{ return Optional.ofNullable( ClassLoader.getSystemClassLoader().getResource( Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()) .getPackage().getName().replaceAll("\\.", "/") + "/" + path ) ).map(u->{ try{ return new File(u.toURI()); }catch(URISyntaxException e){ throw new RuntimeException(e); } }).orElseThrow(()->new IOException(path + " is not Found")); }catch(ClassNotFoundException e){ throw new RuntimeException(e); } }
↑より、ファイルを同じPATH に配置したクラスを指定する方が良いと思う。
public File getPathFile(Class<?> cls, String path) throws IOException{ try{ return new File(ClassLoader.getSystemClassLoader() .getResource(cls.getPackage().getName().replaceAll("\\.", "/") + "/" + path).toURI()); }catch(URISyntaxException e){ throw new RuntimeException(e); } }
通常、Java アーキテクチャのスタイルとして、Java クラスと同じ場所に
リソース扱いのファイルなど置かないのであろうが、
クラスと同じ場所に置いた方が管理しやすい場合もあるだろう。
oboe2uran.hatenablog.com