我想將一個字串放入a中MappedByteBuffer,所以我先將字串轉換為位元組陣列并將其放入緩沖區,但是當我呼叫該.hasArray()方法時它回傳false,問題出在哪里?
這是我的代碼:
package server;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Server {
public static void main(String[] args) throws IOException {
Path path = Paths.get("F:\\Studying\\operating system\\OSTask1\\file.txt");
FileChannel ch = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.READ);
MappedByteBuffer buf = ch.map(FileChannel.MapMode.READ_WRITE, 0, 4096);
String s = "hello world";
byte[] arr = s.getBytes(StandardCharsets.UTF_8);
buf.wrap(arr);
System.out.println(buf.hasArray());
}
}
uj5u.com熱心網友回復:
buf.wrap(arr)回傳新的 ByteBuffer。因此,將您的代碼更改為:
ByteBuffer byteBuffer = buf.wrap(arr);
System.out.println(byteBuffer.hasArray());
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451014.html
