Created
June 21, 2016 04:19
-
-
Save ksharpdabu/b66b54569e2c3bd9f7df31d4dc0537be to your computer and use it in GitHub Desktop.
java使用NIO读取中文乱码的解决办法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.io.RandomAccessFile; | |
import java.nio.ByteBuffer; | |
import java.nio.CharBuffer; | |
import java.nio.channels.FileChannel; | |
import java.nio.charset.Charset; | |
import java.nio.charset.CharsetDecoder; | |
/** | |
* java使用NIO读取中文乱码的解决办法 | |
*/ | |
public class TestFileChannel { | |
public static void main(String[] args) { | |
try { | |
// 通过设置字符集的编码,并将ByteBuffer转换为CharBuffer来避免中文乱码 | |
Charset charset = Charset.forName("UTF-8"); | |
CharsetDecoder decoder = charset.newDecoder(); | |
RandomAccessFile file = new RandomAccessFile("F:\\testB.txt","rw"); | |
FileChannel fileChannel = file.getChannel(); | |
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); | |
CharBuffer charBuffer = CharBuffer.allocate(1024); | |
int byteread = fileChannel.read(byteBuffer); | |
while ( -1 != byteread){ | |
System.out.println("read"+ byteread ); | |
byteBuffer.flip(); | |
while ( byteBuffer.hasRemaining() ){ | |
decoder.decode(byteBuffer,charBuffer,false); | |
charBuffer.flip(); | |
System.out.print( charBuffer); | |
} | |
byteBuffer.clear(); | |
charBuffer.clear(); | |
byteread = fileChannel.read(byteBuffer); | |
} | |
fileChannel.close(); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment