您的位置:首页 > 编程语言

NIO 中文乱码问题的解决代码实现

2016-11-15 15:46 423 查看
之前在网上查询了很多关于解决NIO中文乱码的问题,仁者见仁智者见智,不过就找到的几种方法实现都太繁琐了,稍微研究了下NIO源码,以下是我自己的一种实现,偷懒用最简单的代码去实现是我的习惯!

Demo:

String backupPath = "备份文件夹的路径";

backupPath += File.separator + "ERROR";

File file = new File(filePath);

File backupDirectory = new File("需要复制的文件夹全路径");

if(!backupDirectory.exists()) {
backupDirectory.mkdir();
}
//创建临时文件
File backupFile = new File(backupPath + File.separator + file.getName());

backupFile.createNewFile();

FileOutputStream fos = new FileOutputStream(backupFile, false);

FileInputStream fis = new FileInputStream(file);
//获取输入通道
FileChannel fc_in = fis.getChannel();
//获取输出通道
FileChannel fc_out = fos.getChannel();
//创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(102400);  //这里用1 或者 一个很大的数 比如1024比较小的数也是有几率出现乱码的

CharBuffer charBuffer = CharBuffer.allocate(102400);

char[] charCache = null;

//字符编码
Charset charset = Charset.forName("GBK");

CharsetDecoder charDecoder = charset.newDecoder();

//读取数据到缓冲区
while((fc_in.read(buffer)) != -1) {
buffer.flip();

charDecoder.decode(buffer, charBuffer, true);

charBuffer.flip();

charCache =  new char[charBuffer.length()];

while (charBuffer.hasRemaining()) {

charBuffer.get(charCache);

String str = new String(charCache);

System.out.println(str);

buffer = ByteBuffer.wrap(str.getBytes());
}

fc_out.write(buffer);

charBuffer.clear();

buffer.clear();

}

fis.close();

fos.close();








                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐