1、我们一般以行的方式来读取文本文件的
下面是用例: BufferedReader/BufferedWriter
读:
写:
out = new OutputStreamWriter(new FileOutputStream(file),“GBK”);
bfw = new BufferWriter(out);
源文件中的编码方式为UTF-8,输出时也为UTF-8,结果输出乱码,问题出在FileReader读取文件的
程中,FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数。
所以FileReader只能按系统默认的字符集来解码,然后在UTF-8 -> GBK -> UTF-8的过程中编码出现损
失,造成结果不能还原最初的字符。
原因明确了,这个问题解决起来并不困难,用InputStreamReader代替FileReader,
InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName),“UTF-8”);
这样读取文件就会直接用UTF-8解码,不用再做编码转换。
例如:
读:
/**
* 将文本中的数据解析到ArrayList中
* @param fileName 文件名:全路径
* @return 解析后的List数据集
*/
public static ArrayList<String> fileData2List(String fileName) {
BufferedReader bfr = null;
InputStreamReader in = null;
String encoding = "GBK";
ArrayList<String> arrayList = new ArrayList<String>();
try {
File file = new File(fileName);
if (file.isFile() && file.exists()) {
in = new InputStreamReader(new FileInputStream(file), encoding);
bfr = new BufferedReader(in);
String line = null;
while ((line = bfr.readLine()) != null) {
if(!StringUtils.isBlank(line))
arrayList.add(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}