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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值