Java读写txt文件中文乱码问题

代码中设置编码


1、写文件:

public static void writeFile(String fileName, String fileContent) 
{   
try 
{    
File f = new File(fileName);    
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、读文件:

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; 

你可能感兴趣的:(java文件处理)