Implementation of the solution to the problem of NIO Chinese garbled characters

I have inquired a lot about the problem of solving NIO Chinese garbled characters on the Internet before. The benevolent sees the benevolent and the wise sees the wisdom. However, the implementation of the several methods found are too cumbersome. After a little research on the NIO source code, the following is my own implementation. The simplest code to implement is my habit!

Demo:


  1. String backupPath =  "Path to backup folder" ;  
  2.   
  3. backupPath += File.separator + "ERROR";  
  4.   
  5. File file = new File(filePath);  
  6.   
  7. File backupDirectory =  new  File( "The full path of the folder to be copied" );  
  8.   
  9. if(!backupDirectory.exists()) {  
  10.     backupDirectory.mkdir();  
  11. }  
  12. //create temporary file  
  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. //get the input channel  
  21. FileChannel fc_in = fis.getChannel();  
  22. //get the output channel  
  23. FileChannel fc_out = fos.getChannel();  
  24. //create buffer  
  25. ByteBuffer buffer = ByteBuffer.allocate( 102400 );   //Use 1 or a very large number here, such as 1024, which is a relatively small number, and there is a chance of garbled characters  
  26.   
  27. CharBuffer charBuffer = CharBuffer.allocate(102400);  
  28.   
  29. char[] charCache = null;  
  30.   
  31. //Character Encoding  
  32. Charset charset = Charset.forName("GBK");  
  33.   
  34. CharsetDecoder charDecoder = charset.newDecoder();  
  35.   
  36. //read data into buffer  
  37. while((fc_in.read(buffer)) != -1) {  
  38.     buffer.flip();  
  39.       
  40.     charDecoder.decode(buffer, charBuffer, true);  
  41.       
  42.     charBuffer.flip();  
  43.       
  44.     charCache =  newchar[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();  


  1.   
 
 
 
 
 
 
 
 
 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325302442&siteId=291194637