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


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

    Demo:


    1. String backupPath = "备份文件夹的路径";  
    2.   
    3. backupPath += File.separator + "ERROR";  
    4.   
    5. File file = new File(filePath);  
    6.   
    7. File backupDirectory = new File("需要复制的文件夹全路径");  
    8.   
    9. if(!backupDirectory.exists()) {  
    10.     backupDirectory.mkdir();  
    11. }  
    12. //创建临时文件  
    13. File backupFile = new File(backupPath + File.separator + file.getName());  
    14.   
    15. backupFile.createNewFile();  
    16.   
    17. FileOutputStream fos = new FileOutputStream(backupFile, false);  
    18.   
    19. FileInputStream fis = new FileInputStream(file);  
    20. //获取输入通道  
    21. FileChannel fc_in = fis.getChannel();  
    22. //获取输出通道  
    23. FileChannel fc_out = fos.getChannel();  
    24. //创建缓冲区  
    25. ByteBuffer buffer = ByteBuffer.allocate(102400);  //这里用1 或者 一个很大的数 比如1024比较小的数也是有几率出现乱码的  
    26.   
    27. CharBuffer charBuffer = CharBuffer.allocate(102400);  
    28.   
    29. char[] charCache = null;  
    30.   
    31. //字符编码  
    32. Charset charset = Charset.forName("GBK");  
    33.   
    34. CharsetDecoder charDecoder = charset.newDecoder();  
    35.   
    36. //读取数据到缓冲区  
    37. while((fc_in.read(buffer)) != -1) {  
    38.     buffer.flip();  
    39.       
    40.     charDecoder.decode(buffer, charBuffer, true);  
    41.       
    42.     charBuffer.flip();  
    43.       
    44.     charCache =  new char[charBuffer.length()];   
    45.       
    46.     while (charBuffer.hasRemaining()) {  
    47.           
    48.         charBuffer.get(charCache);  
    49.           
    50.         String str = new String(charCache);  
    51.           
    52.         System.out.println(str);  
    53.           
    54.         buffer = ByteBuffer.wrap(str.getBytes());  
    55.     }  
    56.       
    57.     fc_out.write(buffer);  
    58.       
    59.     charBuffer.clear();  
    60.       
    61.     buffer.clear();  
    62.       
    63. }  
    64.   
    65. fis.close();  
    66.   
    67. fos.close();  
  • 相关阅读:
    CF101B Buses
    CF1C Ancient Berland Circus
    学习笔记 莫比乌斯反演简单整理
    P3768 简单的数学题
    P2508 [HAOI2008]圆上的整点
    CF19E Fairy
    P1295 [TJOI2011]书架
    CF1148B Born This Way
    CF13E Holes
    CF1148C Crazy Diamond
  • 原文地址:https://www.cnblogs.com/jpfss/p/8991448.html
Copyright © 2020-2023  润新知