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

猜你喜欢

转载自blog.csdn.net/Tank_666/article/details/107693570