Javaでテキストファイルを読み込む方法(コピペ用)
Javaでテキストファイルを読み込む方法をよく忘れるのでコピペ用にメモ
コピペ用コード:テキストファイル読み込み
/** * 指定ファイルをテキストファイルとして全データを読み込む。 * * @param file * 読み込むファイル * @param charset * 読み込むファイルの文字コード * @return 読み込んだ結果 * @throws RuntimeException */ public final List<String> readTextFile(final File file, final String charset) { if (file == null) { throw new IllegalArgumentException("引数(file)がnullです。"); } if (charset == null || charset.isEmpty()) { throw new IllegalArgumentException("引数(charset)がnullまたは空文字です。"); } // 終了処理が必要な非メモリリソースは必ずtry/catch文の外で宣言すること FileInputStream is = null; InputStreamReader isr = null; BufferedReader reader = null; final List<String> textList = new ArrayList<String>(); try { is = new FileInputStream(file); isr = new InputStreamReader(is, charset); reader = new BufferedReader(isr); while (reader.ready()) { String text = reader.readLine(); textList.add(text); } } catch (FileNotFoundException e) { throw new RuntimeException("ファイルが見つかりませんでした。file=" + file, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("指定した文字コードはサポートされていません。charset=" + charset, e); } catch (IOException e) { throw new RuntimeException("ファイル読み込み中にIOエラーが発生しました。file=" + file, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.error("IOリソース開放失敗(BufferedReader)", e); } } if (isr != null) { try { isr.close(); } catch (IOException e) { logger.error("IOリソース開放失敗(InputStreamReader)", e); } } if (is != null) { try { is.close(); } catch (IOException e) { logger.error("IOリソース開放失敗(FileInputStream)", e); } } } return textList; }