write file in memory with java.nio?

2019-04-28 17:19发布

问题:

With nio it is possible to map an existing file in memory. But is it possible to create it only in memory without file on the hard drive ?

I want to mimic the CreateFileMapping windows functions which allow you to write in memory.

Is there an equivalent system in Java ?

The goal is to write in memory in order for another program ( c ) to read it.

回答1:

Have a look at the following. A file is created but this might be as close as your going to get.

MappedByteBuffer
MappedByteBuffer.load()
FileChannel
FileChannel.map()

Here is a snippet to try and get you started.

    filePipe = new File(tempDirectory, namedPipe.getName() + ".pipe");
    try {
        int pipeSize = 4096;
        randomAccessFile = new RandomAccessFile(filePipe, "rw");
        fileChannel = randomAccessFile.getChannel();
        mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, pipeSize);
        mappedByteBuffer.load();
    } catch (Exception e) {
    ...


回答2:

A file exists on the disk, by definition. Your question embodies a contradiction in terms.



回答3:

Most libraries in Java deal with input and output streams as opposed to java.io.File objects.
Examples: image reading, XML, audio, zip

Where possible, when dealing with I/O, use streams.

This may not be what you want, however, if you need random access to the data.

When using memory mapped files, and you get a MappedByteBuffer from a FileChannel using FileChannel.map(), if you don't need a file just use a ByteBuffer instead, which exists totally in memory. Create one of these using ByteBuffer.allocate() or ByteBuffer.allocateDirect().