0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[スニペット] Java8 CSVヘッダーをマップで置換

Last updated at Posted at 2025-04-07
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class CSVHeaderReplace {
    public static void main(String[] args) throws IOException {
        String inputFile = "input.csv";
        String outputFile = "output.csv";

        // 英語→和名のマッピング
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Name", "名前");
        headerMap.put("Math", "数学");
        headerMap.put("Science", "理科");
        headerMap.put("English", "英語");

        try (
            CSVReader reader = new CSVReader(new FileReader(inputFile));
            CSVWriter writer = new CSVWriter(new FileWriter(outputFile))
        ) {
            List<String[]> allRows = reader.readAll();
            if (allRows.isEmpty()) return;

            // 最初の行 = ヘッダー
            String[] originalHeader = allRows.get(0);
            String[] replacedHeader = Arrays.stream(originalHeader)
                    .map(col -> headerMap.getOrDefault(col, col)) // 対応がない場合はそのまま
                    .toArray(String[]::new);

            writer.writeNext(replacedHeader);

            // 2行目以降はデータ行としてそのまま書き出し
            for (int i = 1; i < allRows.size(); i++) {
                writer.writeNext(allRows.get(i));
            }
        }
    }
}

import com.opencsv.CSVReader;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HeaderMappingLoader {

    public static Map<String, String> loadHeaderMap(String mappingFilePath) throws IOException {
        Map<String, String> map = new HashMap<>();

        try (CSVReader reader = new CSVReader(new FileReader(mappingFilePath))) {
            String[] line;
            while ((line = reader.readNext()) != null) {
                if (line.length >= 2) {
                    String key = line[0].trim();
                    String value = line[1].trim();
                    map.put(key, value);
                }
            }
        }

        return map;
    }
}
CSVWriter writer = new CSVWriter(
    new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8),
    CSVWriter.DEFAULT_SEPARATOR,
    CSVWriter.NO_QUOTE_CHARACTER,
    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
    System.lineSeparator()
);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?