Introduction to the method of preventing Chinese garbled problems when reading and writing txt files in Java _java

Source: Internet
Author: User

Problem: When using Java program to read and write a TXT file containing Chinese, often read out or write content will appear garbled. The reason is actually very simple, that is, the coding of the system and the coding of the program adopt different coding format. In general, if you do not modify, Windows itself in the encoding format is GBK (and GBK and gb2312 is basically the same encoding), and the IDE encode do not modify, the default is Utf-8 encoding, which is why there will be garbled reasons. When manually created and written in the OS TXT file (GBK), with the program to read directly (Utf-8), will be garbled. In order to avoid possible Chinese garbled problems, it is best to specify the encoding format explicitly when the file is written and read out.

1, write the file:

public static void WriteFile (string filename, string filecontent)  
{   
  try  
  {   
    File f = new File (fileName); C5/>if (!f.exists ())  
    {    
      f.createnewfile ();   
    }   
    OutputStreamWriter write = new OutputStreamWriter (new FileOutputStream (f), "GBK");   
    BufferedWriter writer=new BufferedWriter (write);     
    Writer.write (filecontent);   
    Writer.close ();   
  } catch (Exception e)  
  {   
    e.printstacktrace ();   
  } 
} 

2, read the file:

public static string ReadFile (String fileName) 
{   
  string filecontent = "";   
  Try  
  {    
    file F = new file (fileName);   
    if (F.isfile () &&f.exists ()) 
    {    
      InputStreamReader read = new InputStreamReader (new FileInputStream (f), "GBK");    
      BufferedReader reader=new BufferedReader (read);    
      String Line;    
      while (line = Reader.readline ())!= null)  
      {    
        filecontent + = line;    
      }     
      Read.close ();   
    }   
  catch (Exception e)  
  {     
    e.printstacktrace ();   
  }   
  return filecontent;  
}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.