Javaでsrc/main/resources以下のファイルを読み書きする方法を解説します。
一つの文字列として読み込む
まずは、ファイルに書かれている内容をString型の変数に格納する方法です。
この場合、複数行のファイルでも一つの文字列として読み込まれます。
File file = new File(getClass().getClassLoader().getResource("ファイル名").getFile()); String str = Files.readString(file.toPath(), StandardCharsets.UTF_8);
文字列のリストとして読み込む
次に、ファイルに書かれている内容をString型のListとして読み込む方法です。
File file = new File(getClass().getClassLoader().getResource("ファイル名").getFile()); return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
ファイルが複数行の場合は、基本的にこちらを使う機会の方が多いと思います。