|
| 1 | +package modern.challenge; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.lang.foreign.Arena; |
| 5 | +import java.lang.foreign.MemorySegment; |
| 6 | +import java.nio.channels.FileChannel; |
| 7 | +import static java.nio.channels.FileChannel.MapMode.READ_WRITE; |
| 8 | +import java.nio.file.Path; |
| 9 | +import static java.nio.file.StandardOpenOption.CREATE; |
| 10 | +import static java.nio.file.StandardOpenOption.CREATE_NEW; |
| 11 | +import static java.nio.file.StandardOpenOption.READ; |
| 12 | +import static java.nio.file.StandardOpenOption.SPARSE; |
| 13 | +import static java.nio.file.StandardOpenOption.WRITE; |
| 14 | + |
| 15 | +public class Main { |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + |
| 19 | + try (FileChannel file = FileChannel.open( |
| 20 | + Path.of("readme.txt"), CREATE, READ, WRITE); |
| 21 | + Arena arena = Arena.ofConfined()) { |
| 22 | + |
| 23 | + MemorySegment segment |
| 24 | + = file.map(READ_WRITE, 0, 1048576, arena); // 1 Megabyte = 1048576 bytes |
| 25 | + // 1 Gigabyte = 1073741824 bytes |
| 26 | + |
| 27 | + // write the data |
| 28 | + segment.setString(0, "This is a readme file ..."); |
| 29 | + segment.setString(1048576/2, "Here is the middle of the file ..."); |
| 30 | + segment.setString(1048576-32, "Here is the end of the file ..."); |
| 31 | + |
| 32 | + // read some data |
| 33 | + System.out.println(segment.getString(1048576/2)); |
| 34 | + } |
| 35 | + |
| 36 | + try (FileChannel file = FileChannel.open( |
| 37 | + Path.of("sparse_readme.txt"), CREATE_NEW, SPARSE, READ, WRITE); |
| 38 | + Arena arena = Arena.ofConfined()) { |
| 39 | + |
| 40 | + MemorySegment segment |
| 41 | + = file.map(READ_WRITE, 0, 1048576, arena); // 1 Megabyte = 1048576 bytes |
| 42 | + // 1 Gigabyte = 1073741824 bytes |
| 43 | + |
| 44 | + // write the data |
| 45 | + segment.setString(0, "This is a readme file ..."); |
| 46 | + segment.setString(1048576/2, "Here is the middle of the file ..."); |
| 47 | + segment.setString(1048576-32, "Here is the end of the file ..."); |
| 48 | + |
| 49 | + // read some data |
| 50 | + System.out.println(segment.getString(0)); |
| 51 | + } |
| 52 | + |
| 53 | + System.out.println("\n\nYou should find the files on disk in the project's root"); |
| 54 | + } |
| 55 | +} |
0 commit comments