您的位置:首页 > 编程语言 > Java开发

Java文本读写

2016-12-04 09:44 399 查看
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 fileData2List(String fileName) {

BufferedReader bfr = null;

InputStreamReader in = null;

String encoding = “GBK”;

ArrayList arrayList = new ArrayList();

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 文本读写