CSV Java生成的文件使用不正确的Charset打开

时间:2016-07-18 14:14:32

标签: java csv utf-8

以下是用于生成CSV文件的java代码。虽然在调试时report.getEncoding()获取了“UTF-8”的值,但生成的文件的字符集不正确。

public void generateFile(ReportBean<T> report, String filename, ReportAggregationPosition reportAggregationPosition) throws IOException {
    try (PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), report.getEncoding()))) {
        List<T> filteredResult = new ArrayList();
        for (T row : report.getResult()) {
            if (logRow(row)) {
                log.info("Logging row for report={} - {}", filename, getText(row));
            }
            if (ignoreRow(row)) {
                log.info("Ignoring row for report={} - {}", filename, getText(row));
                continue;
            }
            filteredResult.add(row);
        }
        if (reportAggregationPosition == ReportAggregationPosition.FIRST) {
            out.println(filteredResult.size());
        }
        out.print(getHeader());
        if (reportAggregationPosition == ReportAggregationPosition.SECOND) {
            out.println(filteredResult.size());
        }
        for (T row : filteredResult) {
            out.print(getText(row));
        }
        if (reportAggregationPosition == ReportAggregationPosition.LAST) {
            out.println(String.format("Total number of rows: %s", filteredResult.size()));
        }
    }

预期值为:

  

test-vfde - 隐藏版 - GebührproBenutzer Leistungszeit 07/07/16 bis 08/05/16

但显示的价值(我无法上传照片,因为我仍然没有积分)是以下一个:

  

test-vfde - 隐藏版 - GebÇŸ'?Ç?¶¬hrproBenutzer Leistungszeit 07/07/16 bis 08/05/16

正确显示“ä”或“ü”字符。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

尝试添加以下行

.....
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), report.getEncoding()))) {
    out.write(0xef);
    out.write(0xbb);
    out.write(0xbf);
    List<T> filteredResult = new ArrayList();
    .....

说明可以找到here