Mapped Memory Segment / Read from an existing file written via FileChannel or RandomAccessFile
Johannes Lichtenberger
lichtenberger.johannes at gmail.com
Thu Mar 31 23:28:37 UTC 2022
Hello,
I'm currently not sure what I'm doing wrong, but the following test is not
working. Maybe it's too late, but I'm not sure if I'll have an immediate
idea tomorrow, so I guess it's best to ask for help :-)
kind regards
Johannes
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.ResourceScope;
import jdk.incubator.foreign.ValueLayout;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestFileChannelWithMemorySegment {
private Path tempFile;
@BeforeEach
public void setup() {
tempFile = Paths.get(System.getProperty("java.io.tmpdir"), "test.bin");
}
@AfterEach
public void tearDown() throws IOException {
Files.delete(tempFile);
}
@org.junit.jupiter.api.Test
public void test() throws IOException {
// try (final FileChannel fileChannel = FileChannel.open(tempFile,
//
StandardOpenOption.CREATE_NEW,
//
StandardOpenOption.WRITE)) {
// final ByteBuffer byteBuffer = ByteBuffer.allocate(8);
// byteBuffer.putLong(11);
// byteBuffer.position(0);
//
// fileChannel.write(byteBuffer);
// fileChannel.force(true);
// }
try (final RandomAccessFile randomAccessFile = new
RandomAccessFile(tempFile.toFile(), "rw")) {
randomAccessFile.writeLong(11);
}
try (final ResourceScope resourceScope = ResourceScope.newSharedScope()) {
final MemorySegment memorySegment =
MemorySegment.mapFile(tempFile, 0, Files.size(tempFile),
FileChannel.MapMode.READ_ONLY, resourceScope);
final var longVal = memorySegment.get(ValueLayout.JAVA_LONG, 0);
assertEquals(11, longVal);
}
}
}
More information about the panama-dev
mailing list