【Java学习笔记二】读写中文文件,包含乱码问题

因为Windows系统默认编码模式为gbk,而程序直接去读文件的话默认是utf-8模式,所以会出现乱码问题,所以在读文件的时候要指定编码格式。

解决方法:采用 java.io.FileInputStream 和 java.io.InputStreamReader

代码如下,读取txt文件,按行存入列表中,返回列表做后续分析。

public static List<String> readline(String filename)
{
    File file = new File(filename);
    InputStream in = null;
    BufferedReader reader = null;
    List<String> sentences = new LinkedList<>();
    try{
        //System.out.println("以行为单位读取文件内容,一次读一整行");
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));
        String line = null;
        while ((line = reader.readLine())!= null){
            sentences.add(line);
        }
        reader.close();
    }
    catch (FileNotFoundException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }finally {
        if(reader != null){
            try{
                reader.close();
            }catch (IOException el){
            } } }
    return sentences;
}

学习笔记:

1.FileInputStream :从文件系统的某个文件中获得输入字节,字节流。

2.FileReader :从文件系统的某个文件中获得输入字符,字符流,一个中文字是两个字节,一个字符。

3.FileInputStream 可以设置编码格式,FileReader 不可以。

4.InputStreamReader :从字节流到字符流的桥接器,它使用指定的字符集读取字节并将它们解码为字符。 它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。

5.BufferedReader :从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

 reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));

这一句就完成了读文件:字节——字符——文本的过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值