New IO 讀寫文件,編碼出現問題!

最近在做一個FileUtil,技術採用New IO, 在做的時候出現了編碼問題!
例如:
我採用writeFile("D:\test.txt","中國",null)
然後我用readFile("D:\test.txt")讀結果就會返回亂碼!
後來我用Charset解碼 , 獲取目標文件編碼(System.getProperty("file.encoding")),但是還是不行.
估計我應該要獲得目標文件字節流的編碼,這樣才能根據相應的編碼去讀文件.
我怎麼樣才能判斷目標文件的字節流編碼呢?
或許我們會有更好的辦法.請各位指教?謝謝!


// 讀文件採用的字符編碼.
private static Charset charset = Charset.forName(System.getProperty("file.encoding"));
/**
* 讀文件
* @param fileName
* @return 讀入的字符串
*/
public String readFile(String fileName){
CharBuffer cb = null;
try {
FileChannel in = new FileInputStream(fileName).getChannel();
int size = (int)in.size();
MappedByteBuffer mppedByteBuffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
cb = charset.newDecoder().decode(mppedByteBuffer);
in.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
return cb.toString();
}

/**
* 創建文件(寫文件)
* @param fileName 文件名
* @param content 內容
* @param encoding 編碼 (就是你需要以哪一種編碼格式進行寫入) . 默認採用(utf-8).
* @return true 創建成功 ,false 創建失敗
*/
public boolean writeFile(String fileName,String content,String encoding){
try{
FileChannel out = new FileOutputStream(fileName).getChannel();
encoding = encoding == null ? "" : encoding;
if(encoding.length() <= 0)
encoding = "utf-8";
out.write(ByteBuffer.wrap(content.getBytes(encoding)));
out.close();
return true;
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return false;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章