1

我有一个内存映射文件,我可以在其中写入如下值:

public class HelloWorld{

    public static void main(String []args){

        try {
            // OPEN MAPPED MEMORY FILE
            file = new RandomAccessFile("myMemoryMappedFile", "rw");

            // ASSIGN BUFFER
            fileBuffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1024);

            // INITIALIZE ALL FILE TO 1
            for (int i = 0; i < fileSize; i++)
            {
                fileBuffer.put((byte) 1);
            }

            MyClass myClass = new MyClass();
            myClass.writeExternal(???????);    // HOW DO I LINK THE fileBuffer and the ObjectOutput?

        } catch (FileNotFoundException ex) {
            System.err.println("Error while opening a new database: file not found.");
            return false;

        } catch (IOException ex) {
            System.err.println("Error while opening a new database: IO exception.");
            return false;
        }

    }

}

我有一个实现Externalizable覆盖writeExternal方法的类:

public class MyClass implements Externalizable {

    public long epochBegin = -1;
    public long epochEnd = -1;
    public int data = -1;

    public MyClass(){
    };    

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {

        byte[] epochBeginByte = ByteBuffer.allocate(4).putInt((int)this.epochBegin).array();
        byte[] epochEndByte = ByteBuffer.allocate(4).putInt((int)this.epochEnd).array();
        byte[] dataByte = ByteBuffer.allocate(4).putInt((int)this.data).array();

        out.write(epochBeginByte);
        out.write(epochEndByte);
        out.write(dataByte);

        out.flush();

    }

}

我想在位置 10 字节writeExternal的内存映射文件上调用该方法。myMemoryMappedFile所以在文件中,第 10 个字节将有 12 个字节包含变量this.epochBegin,this.epochEnddata.

不幸的是,我完全不知道如何链接这两个东西,内存映射文件和writeExternal过程。欢迎任何有关如何继续的提示。

4

0 回答 0