Java讀寫txt文件時防止中文亂碼問題出現(xiàn)的方法介紹
問題:在用Java程序進行讀寫含中文的txt文件時,經(jīng)常會出現(xiàn)讀出或?qū)懭氲膬?nèi)容會出現(xiàn)亂碼。原因其實很簡單,就是系統(tǒng)的編碼和程序的編碼采用了不同的編碼格式。通常,假如自己不修改的話,windows自身采用的編碼格式是gbk(而gbk和gb2312基本上是一樣的編碼方式),而IDE中Encode不修改的話,默認是utf-8的編碼,這就是為什么會出現(xiàn)亂碼的原因。當(dāng)在OS下手工創(chuàng)建并寫入的txt文件(gbk),用程序直接去讀(utf-8),就會亂碼。為了避免可能的中文亂碼問題,最好在文件寫入和讀出的時候顯式指定編碼格式。
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;
}
相關(guān)文章
關(guān)于@RequestBody和@RequestParam注解的使用詳解
這篇文章主要介紹了關(guān)于@RequestBody和@RequestParam注解的使用詳解,本文十分具有參考意義,希望可以幫助到你,如果有錯誤的地方還望不吝賜教2023-03-03
Spring Security實現(xiàn)自定義訪問策略
本文介紹Spring Security實現(xiàn)自定義訪問策略,當(dāng)根據(jù)誰訪問哪個域?qū)ο笞龀霭踩珱Q策時,您可能需要一個自定義的訪問決策投票者,幸運的是,Spring Security有很多這樣的選項來實現(xiàn)訪問控制列表(ACL)約束,下面就來學(xué)習(xí)Spring Security自定義訪問策略,需要的朋友可以參考下2022-02-02
java線程池ThreadPoolExecutor類使用小結(jié)
這篇文章主要介紹了java線程池ThreadPoolExecutor類使用,本文主要對ThreadPoolExecutor的使用方法進行一個詳細的概述,示例代碼介紹了ThreadPoolExecutor的構(gòu)造函數(shù)的相關(guān)知識,感興趣的朋友一起看看吧2022-03-03

