java读取文件中文乱码解决

背景:

java程序读取服务器上的文件,通过vi 的命令查看文件编码为set fileencoding = latbin1.

 

java本来的读取方式为:问题是中文乱码

 

方法一:

public class TestRead {    

 

    public static void main(String[] args) {    

        try {    

            BufferedReader reader = new BufferedReader(new FileReader("*.txt"));//换成你的文件名   

            reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉   

            String line = null;    

            while((line=reader.readLine())!=null){    

                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分   

 

                String last = item[item.length-1];//这就是你要的数据了   

                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值   

                System.out.println(last);    

            }    

        } catch (Exception e) {    

            e.printStackTrace();    

        }    

    }    

 

}

 

这种方式读取到的文件始终是乱码的,通过流方式获取文件,在转成字符流才能解决这个问题。

 

 

方法二:

File f = new File("*.txt");

// InputStreamReader read = new InputStreamReader (new FileInputStream(f),"UTF-8");

 InputStreamReader read = new InputStreamReader (new FileInputStream(f),"GBK");

BufferedReader reader=new BufferedReader(read);

 

String line;

 

while ((line = reader.readLine()) != null) {

 

System.out.println(line);

 

}

 

 

参考资料以及其他的解决方案以供参考:

 

https://blog.csdn.net/iteye_10231/article/details/82301343

https://www.oschina.net/question/2795_74288?sort=time

https://blog.csdn.net/yuxiangaaaaa/article/details/74251504

https://blog.51cto.com/12237592/1968561?source=dra

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值