Java文本读写

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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值