如何将CSV文件中的日语字段读入java bean? [英] How read Japanese fields from CSV file into java beans?

查看:278
本文介绍了如何将CSV文件中的日语字段读入java bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过几个流行的CSV到java解串器 - OpenCSV,JSefa和Smooks - 没有正确读取的文件:

 名字,姓氏
エリック,山中
花子,铃木
一郎,铃木
裕子,田中
政治,山村


OpenCsv代码:

  HeaderColumnNameTranslateMappingStrategy< Contact> strat = new HeaderColumnNameTranslateMappingStrategy< Contact>(); 
strat.setType(Contact.class);
strat.setColumnMapping(colNameTranslateMap);
InputStreamReader fileReader = null;
CsvToBean< Contact> csv = new CsvToBean< Contact>();
fileReader = new InputStreamReader(new FileInputStream(file),UTF-8);

contacts = csv.parse(strat,new CSVReader(fileReader));

我已经尝试将Charset设置为UTF-8,UTF-16和ISO-8859-1当我创建FileInputStream,但集合从未正确填充。如在调试器和System.out中看到的字段包含垃圾,并且通常记录的数量是错误的。

解决方案


  1. FileInputStream code> 用于读取二进制数据流,如mp3或PNG。而不是 FIS ,请使用
  2. 要谨慎:谁关心什么字符集?
  3. 你试过使用,如果他们没有工作?您需要找出实际使用的CSV文件的编码,并在读取文件时设置 编码。使用 FileReader 时指定编码:




此类的构造函数假定默认字符编码和默认字节缓冲区大小是适当的。 要自行指定这些值,请在FileInputStream上构建InputStreamReader。



I've tried several popular CSV to java deserializers - OpenCSV, JSefa, and Smooks - none correctly read the file:

First Name,Last Name
エリック,山中
花子,鈴木
一郎,鈴木
裕子,田中
政治,山村

into my java object collection.

OpenCsv code:

    HeaderColumnNameTranslateMappingStrategy<Contact> strat = new HeaderColumnNameTranslateMappingStrategy<Contact>();
    strat.setType(Contact.class);
    strat.setColumnMapping(colNameTranslateMap);
    InputStreamReader fileReader=null;
    CsvToBean<Contact> csv = new CsvToBean<Contact>();
    fileReader = new InputStreamReader(new FileInputStream(file), "UTF-8");

    contacts = csv.parse(strat, new CSVReader(fileReader));

I've tried setting the Charset to UTF-8, UTF-16 and ISO-8859-1 when I create the FileInputStream, but the collection is never populated properly. As seen in the debugger and System.out the fields contain garbage and often the number of records is wrong.

解决方案

  1. FileInputStream is for reading streams of binary data, like an mp3 or PNG. Instead of a FIS, use a FileReader for reading streams of characters.
  2. To be blunt: who cares what charsets you tried using if they didn't work? You need to figure out what encoding the CSV file is actually using, and set that encoding when reading the file. To specify the encoding when using a FileReader:

The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

这篇关于如何将CSV文件中的日语字段读入java bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆