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:
- String backupPath = "Path to backup folder" ;
- backupPath += File.separator + "ERROR";
- File file = new File(filePath);
- File backupDirectory = new File( "The full path of the folder to be copied" );
- if(!backupDirectory.exists()) {
- backupDirectory.mkdir();
- }
- //create temporary file
- File backupFile = new File(backupPath + File.separator + file.getName());
- backupFile.createNewFile();
- FileOutputStream fos = new FileOutputStream(backupFile, false);
- FileInputStream fis = new FileInputStream(file);
- //get the input channel
- FileChannel fc_in = fis.getChannel();
- //get the output channel
- FileChannel fc_out = fos.getChannel();
- //create buffer
- 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
- CharBuffer charBuffer = CharBuffer.allocate(102400);
- char[] charCache = null;
- //Character Encoding
- Charset charset = Charset.forName("GBK");
- CharsetDecoder charDecoder = charset.newDecoder();
- //read data into buffer
- while((fc_in.read(buffer)) != -1) {
- buffer.flip();
- charDecoder.decode(buffer, charBuffer, true);
- charBuffer.flip();
- charCache = newchar[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();