先日書いた、
クラスと同じclasspath の場所に置いたファイルのIO - Oboe吹きプログラマの黙示録
よくよく考えたら
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); } }
以下の方が良い
public File getCurrentPathFile(String path) throws IOException{ String s = Thread.currentThread().getStackTrace()[2].getClassName(); int n = s.lastIndexOf("."); String f = n < 0 ? path : s.substring(0, n).replaceAll("\\.", "/") + "/" + path; return Optional.ofNullable( ClassLoader.getSystemClassLoader().getResource(f) ).map(u->{ try{ return new File(u.toURI()); }catch(URISyntaxException e){ throw new RuntimeException(e); } }).orElseThrow(()->new IOException(path + " is not Found")); }
あるいは、こちらの方が良い!
public File getCurrentPathFile(String path){ String s = Thread.currentThread().getStackTrace()[2].getClassName(); int n = s.lastIndexOf("."); String f = n < 0 ? path : s.substring(0, n).replaceAll("\\.", "/") + "/" + path; try{ return new File(ClassLoader.getSystemClassLoader().getResource(f).toURI()); }catch(URISyntaxException e){ throw new RuntimeException(e); } }