package NIO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.SortedMap;
public class CharSet {
public static void main(String[] args) throws IOException{
FileInputStream fis=new FileInputStream("c:\\jdk\\a.txt");
FileOutputStream fos=new FileOutputStream("c:\\jdk\\a.txt");
FileChannel fco=fos.getChannel();
String s=new String("142345a陈");
fos.write(s.getBytes("GBK"));
fos.write('1');//写字符不乱码
ByteBuffer bf=ByteBuffer.allocate(100);
bf.put(s.getBytes("GBK"));
bf.clear();//一定不能忘,不然读写都有问题,pointer定位到起点
fco.write(bf);//bf定位到100
System.out.println(bf.capacity());
bf.putChar(10,'x');
bf.clear();
//获取java支持的字符集
/* SortedMap<String, Charset> map=Charset.availableCharsets();
for(String ss:map.keySet()) {
System.out.println(ss+"----->"+map.get(ss));
}*/
Charset cs=Charset.forName("GBK");//(编码解码不一致)文件编码导致的MalformedInputException异常
CharsetDecoder dc=cs.newDecoder();
CharBuffer cb=dc.decode(bf);
System.out.println(cb);
}
}
Charset的基本运用以及ByteBuffer-position的注意点
最新推荐文章于 2021-08-08 19:41:45 发布