问题复现
Phone.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Phone {
private String brand;
private String type;
}
PhoneTest.java
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.file.FileReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
public class PhoneTest {
public static void main(String[] args) {
String filePath = "C:\\Projects\\aap\\phone.txt";
try {
FileReader fr = new FileReader(filePath);
List<String> lines = fr.readLines();
List<Phone> phoneList = new ArrayList<>();
String[] columnNames = lines.get(0).split("\t");
for (int i = 1; i < lines.size(); i++) {
List<String> list = Arrays.asList(lines.get(i).split("\t"));
Map<String, Object> map = new HashMap<>();
for (int j = 0; j < list.size(); j++) {
map.put(columnNames[j], list.get(j));
}
JSONObject jsonObject = new JSONObject(map);
phoneList.add(JSON.toJavaObject(jsonObject, Phone.class));
}
System.out.println(phoneList);
} catch (IORuntimeException e) {
e.printStackTrace();
}
}
}
复现步骤:
1. 本地新建文本phone.txt
2. 从xls中copy数据到phone.txt中,此时phone.txt默认格式为UTF-8-BOM。
3. 查看文本编码格式,用nodepad打开文件,Encoding 即可查看文本编码格式。
运行结果
UTF-8-DOM
如果格式为UTF-8-DOM,则首列数据为null(类的第一个字段)。
[Phone(brand=null, type=12), Phone(brand=null, type=n96), Phone(brand=null, type=5), Phone(brand=null, type=Nova)]
UTF-8
如果格式为UTF-8,正常打印结果。
[Phone(brand=apple, type=12), Phone(brand=nokia, type=n96), Phone(brand=小米, type=5), Phone(brand=华为, type=Nova)]
解决方案
方案1:更改文本编码格式
方案2:读取文件时设置编码格式
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.file.FileReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
public class PhoneTest {
public static void main(String[] args) {
String filePath = "C:\\Projects\\aap\\phone.txt";
try {
FileReader fr = new FileReader(filePath, "UTF-8");
List<String> lines = fr.readLines();
List<Phone> phoneList = new ArrayList<>();
String[] columnNames = lines.get(0).split("\t");
for (int i = 1; i < lines.size(); i++) {
List<String> list = Arrays.asList(lines.get(i).split("\t"));
Map<String, Object> map = new HashMap<>();
for (int j = 0; j < list.size(); j++) {
map.put(columnNames[j], list.get(j));
}
JSONObject jsonObject = new JSONObject(map);
phoneList.add(JSON.toJavaObject(jsonObject, Phone.class));
}
System.out.println(phoneList);
} catch (IORuntimeException e) {
e.printStackTrace();
}
}
}