Home >Java >JavaBase >Solution to Java reading txt garbled characters

Solution to Java reading txt garbled characters

尚
Original
2019-11-20 15:43:583470browse

Solution to Java reading txt garbled characters

If java reads txt text that contains Chinese, garbled characters may appear. The solution is:

1. Unify the encoding, the encoding of java project, txt text Encoding, the java text encoding in the java project is unified to utf-8;

2. Use InputStreamReader(new FileInputStream(fileUrl), "utf-8") to set the text to utf-8 again

InputStreamReader isr;   
    try {   
        isr = new InputStreamReader(new FileInputStream(fileUrl), "utf-8");   
         BufferedReader read = new BufferedReader(isr);   
           String s=null;   
           List<String> list = new ArrayList<String>();   
           while((s=read.readLine())!=null)   
           {   
               //System.out.println(s);   
               if(s.trim().length()>1){   
               list.add(s.trim());   
               }   
           }   
              
           System.out.println("OK!");   
    } catch (UnsupportedEncodingException e) {   
               e.printStackTrace();   
    } catch (FileNotFoundException e) {   
               e.printStackTrace();   
    } catch (IOException e) {   
               e.printStackTrace();   
    }

For more java knowledge, please pay attention to java basic tutorial.

The above is the detailed content of Solution to Java reading txt garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn