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

来源:互联网 发布:spss mac 23 教程 编辑:程序博客网 时间:2024/05/19 00:40

之前在网上查询了很多关于解决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();


                                             
1 0