映射缓冲区读取 int

Mappped buffer read int

我有 2 个简单的函数来写入一个 int 并从映射文件中读取它,但似乎其中一个函数是错误的。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;

public class MemoryMappedFileInJava {

  // file
  File file;
  // channel to connect the file content to buffer
  FileChannel channel;
  // buffer
  MappedByteBuffer buffer;
  // buffer max size in bytes
  final int BUFFER_MAX = 32;

  @SuppressWarnings("resource")
  MemoryMappedFileInJava() {

    file = new File("file.txt");
    //create a channel to write and read
    try {
      channel = new RandomAccessFile(file, "rw").getChannel();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    // map the file content to buffer
    try {
      buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, BUFFER_MAX);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  // read the value from buffer
  int readInt() {
    int number=0;
    int c = buffer.getInt();
    buffer.position(0);
    while (c != '[=10=]')
      number += c;
    return number;
  }

  // send the message to buffer
  void writeInt(int number) {

    buffer.position(0);
    buffer.putInt(number);
    buffer.putChar('[=10=]');
  }

  // close the channel 
  void closeChannel() {
    try {
      channel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  //lets make some tests with random numbers
  static void run() {
    Random r = new Random();
    MemoryMappedFileInJava communication = new MemoryMappedFileInJava();

    int number = r.nextInt(5) + 1;
    communication.writeInt(number);
    String prefix = "the given number from buffer is --> ";

    System.out.print(prefix + communication.readInt());
  }

  public static void main(String[]args)
  {
    run();
  }
}

我用于 运行 这段代码的完整代码也可以从这里编译和 运行: http://tpcg.io/5hOPVh1Q

输出打印总是给出 0,如果是在写函数或读函数中,我找不到问题出在哪里。

我不明白 number 变量或 readInt 方法中的 while 循环的原因。如果您只想从 buffer 的开头读取 int,那么将您的 readInt 方法更改为以下方法就可以了:

    int readInt() {
        buffer.position(0);
        return buffer.getInt();
    }