Solution to Chinese garbled characters when reading files using Java

background:

The java program reads the file on the server and uses the vi command to view the file encoding as set fileencoding = latbin1.

 

The original reading method of java is: the problem is Chinese garbled characters

 

method one:

public class TestRead {    

 

    public static void main(String[] args) {    

        try {    

           BufferedReader reader = new BufferedReader(new FileReader("*.txt"));//replace with your file name   

            reader.readLine();//The first line of information is the title information, no need, comment it out if necessary   

            String line = null;    

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

                String item[] = line.split(",");//CSV format file is a comma delimited file, here it is split according to commas   

 

                String last = item[item.length-1];//This is the data you want   

                //int value = Integer.parseInt(last);//If it is a numerical value, it can be converted into a numerical value   

                System.out.println(last);    

            }    

        } catch (Exception e) {    

            e.printStackTrace();    

        }    

    }    

 

}

 

The files read in this way are always garbled. This problem can be solved by obtaining the file through a stream and converting it into a character stream.

 

 

Method Two:

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);

 

}

 

 

Reference materials and other solutions for reference:

 

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

Guess you like

Origin blog.csdn.net/Tank_666/article/details/107693570