![](/img/trans.png)
[英]What is the difference between ByteBuffer and CharBuffer in Java NIO?
[英]Java NIO Issue on CharBuffer
我正在使用以下代碼從文件中讀取子序列。
FileChannel channel = new RandomAccessFile("abc.txt", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
CharBuffer cbuf = buffer.asCharBuffer();
String str = cbuf.subSequence(0, 1).toString();
System.out.println("str = " + str);
但是,這給出了輸出“str =?” 任何人都可以幫助我為什么會發生這種情況以及如何解決這個問題? 對不起,我是NIO的新手。
另外一件事,當我添加System.out.println(緩沖區); 它給出輸出“java.nio.DirectByteBufferR [pos = 0 lim = 16 cap = 16]”。
System.out.println((char)buffer.get(0))給出正確的輸出意味着第一個字符。
嘗試使用此方法,您有一個編碼問題:
FileChannel channel = new RandomAccessFile("/home/alain/Bureau/clair.txt", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
Charset chars = Charset.forName("ISO-8859-1");
CharBuffer cbuf = chars.decode(buffer);
String str = cbuf.subSequence(0, 10).toString();
System.out.println("str = " + str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.