では、前回の「CSVに保存」した分析結果を、再びプログラムで読み込んで再利用(再分析やグラフ表示などに活用)するサンプルを紹介します。
サンプルコード:CSVを読み込んで再利用
ここでは、前回保存した analysis_result.csv の「値,出現回数」部分を読み込み、再びランキングやグラフ表示に使う例です。
import java.util.*;
import java.io.*;
public class ReadCSVSample {
public static void main(String[] args) {
Map<Integer, Integer> countMap = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader("analysis_result.csv"))) {
String line;
boolean dataSection = false;
while ((line = br.readLine()) != null) {
// 空行をスキップ
if (line.trim().isEmpty()) continue;
// 「値,出現回数」のヘッダーが出たらデータ部分開始
if (line.startsWith("値,出現回数")) {
dataSection = true;
continue;
}
if (dataSection) {
String[] parts = line.split(",");
if (parts.length == 2) {
try {
int value = Integer.parseInt(parts[0]);
int count = Integer.parseInt(parts[1]);
countMap.put(value, count);
} catch (NumberFormatException e) {
System.out.println("数値に変換できません: " + line);
}
}
}
}
} catch (IOException e) {
System.out.println("CSV読み込み中にエラーが発生しました: " + e.getMessage());
}
if (countMap.isEmpty()) {
System.out.println("CSVから有効なデータを読み込めませんでした。");
return;
}
// 出現回数ランキング(降順ソート)
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(countMap.entrySet());
entryList.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
// 結果表示
System.out.println("=== CSVから読み込んだデータ ===");
System.out.println("出現回数ランキング:");
int rank = 1;
for (Map.Entry<Integer, Integer> entry : entryList) {
System.out.println(rank + "位: " + entry.getKey() + "(" + entry.getValue() + "回)");
rank++;
}
System.out.println("\n出現回数グラフ:");
for (Map.Entry<Integer, Integer> entry : entryList) {
String bar = "#".repeat(entry.getValue());
System.out.println(entry.getKey() + " : " + bar + " (" + entry.getValue() + ")");
}
}
}
Java✅ 実行例(前回のCSVを読み込んだ場合)
=== CSVから読み込んだデータ ===
出現回数ランキング:
1位: 10(3回)
2位: 30(2回)
3位: 20(2回)
4位: 40(1回)
出現回数グラフ:
10 : ### (3)
30 : ## (2)
20 : ## (2)
40 : # (1)
ポイント
BufferedReaderで CSV を1行ずつ読み込む- 「ヘッダー行」をスキップしてデータ部分だけ処理
- 読み込んだデータを
Map<Integer, Integer>に格納すれば、再びランキングやグラフに利用可能
発展アイデア
- CSVの「合計・平均・最大・最小」部分も読み込んで再表示する
- 読み込んだデータを 別のCSVに加工して保存(例:上位3位だけ出力)
- Javaの外部ライブラリ(OpenCSVなど)を使うと、より柔軟にCSVを扱える
👉 これで「CSVに保存 → CSVを読み込んで再利用」の流れが完成しました。

