JavaとJavaEEプログラマのブログ

JavaEEを中心にしたをソフトウェア開発についてのブログ

クラスパス内にあるテキストファイルを読み込むサンプル

commonsにもっと便利なメソッドがあったはず。

追記:commons-io http://commons.apache.org/io/ にあるFileUtilsを使えばOK。
使い方:http://java6.blog117.fc2.com/blog-entry-58.html

	/**
	 * クラスパス内にあるテキストファイルの内容をひとつの文字列として読み込む。
	 * テキストファイルの文字コードはUTF-8のみに対応。
	 *
	 * @param filePath テキストファイルへのパス(例:"/com/m-prog/fuga/hoge.txt")
	 *
	 *
	 */
	public String readText(String filePath){

		List<String> textList = new ArrayList<String>();

		StringBuilder b = new StringBuilder();

		InputStream is = this.getClass().getResourceAsStream(filePath);
		Reader r = null;
		BufferedReader br = null;
		try {
			r = new InputStreamReader(is, "UTF-8");
			br = new BufferedReader(r);
			for (;;) {
				String text = br.readLine(); // 改行コードは含まれない
				if (text == null) {
					break;
				}
				textList.add(text);
				b.append(text + "\n");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
				}
			if (r != null)
				try {
					r.close();
				} catch (IOException e) {
				}
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}


		return b.toString();
	}