[英]Converting a String to ByteBuffer
I want to put a string into a MappedByteBuffer
so I converted the string into a byte array first and put it into the buffer, but when I invoke the .hasArray()
method it returns false, where is the problem?我想将一个字符串放入MappedByteBuffer
中,所以我先将字符串转换为字节数组并将其放入缓冲区中,但是当我调用.hasArray()
方法时它返回 false,问题出在哪里?
Here is my code:这是我的代码:
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());
}
}
buf.wrap(arr)
returns the new ByteBuffer. buf.wrap(arr)
返回新的 ByteBuffer。 So change your code to:因此,将您的代码更改为:
ByteBuffer byteBuffer = buf.wrap(arr);
System.out.println(byteBuffer.hasArray());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.