NIO 中文乱码问题的解决代码实现
2016-11-15 15:46
423 查看
之前在网上查询了很多关于解决NIO中文乱码的问题,仁者见仁智者见智,不过就找到的几种方法实现都太繁琐了,稍微研究了下NIO源码,以下是我自己的一种实现,偷懒用最简单的代码去实现是我的习惯!
Demo:
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();
相关文章推荐
- vb.net从DataGridView复制到Excel.代码实现,解决中文乱码问题 (转载+亲自实践)
- Java底层代码实现单文件读取和写入(解决中文乱码问题)
- java代码中实现字符编码转换(解决中文乱码问题)
- php中强制下载文件的代码(解决了IE下中文文件名乱码问题)
- php的IMAP的应用实例(实现收发邮件、删除邮件、附件下载等功能,解决中文乱码问题)
- Java Web中使用JSPSmartUpload控件实现文件的上传和下载(解决了中文乱码问题)(JSP页面采用GBK编码)
- jsp实现文件下载与中文文件名乱码问题解决
- javadbf 实现解决中文乱码问题
- jsp实现文件下载与中文文件名乱码问题解决
- java实现中文文件下载,解决乱码问题,亲测无问题~~
- jsp实现文件下载与中文文件名乱码问题解决
- Java实现Zip压缩与解压(解决中文乱码问题)
- JSP实现文件下载同时解决中文乱码问题
- Domino中Servlet实现RSS中文乱码问题解决
- 如何解决ASP.NET下载时的中文文件名乱码,与TXT文件中存在代码两个问题
- 使用Qt Visual Studio Add-in 实现中文ts文件,解决中文乱码问题
- php的IMAP的应用实例(实现收发邮件、删除邮件、附件下载等功能,解决中文乱码问题)
- 实现文件下载与中文文件名乱码问题解决
- 崩溃,source Insight显示linux代码中文注释乱码问题,以及很傻很天真的解决方法
- 利用org.apache.commons.net.ftp实现ftp下载,解决中文文件名乱码问题