Home > Mobile >  Converting a String to ByteBuffer
Converting a String to ByteBuffer

Time:03-28

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 ?

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());
    }
    
}

CodePudding user response:

buf.wrap(arr) returns the new ByteBuffer. So change your code to:

ByteBuffer byteBuffer = buf.wrap(arr);
System.out.println(byteBuffer.hasArray());
  • Related