6

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.

Foobyto
  • 119
  • 1
  • 7

2 Answers2

3

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) {
    ...
Java42
  • 7,628
  • 1
  • 32
  • 50
  • This work and indeed, everything is in RAM (i check with some utilities, no hdd i/o) But, do you know how to retrieve the mapped file with c code ? using window function ? – Foobyto Mar 23 '12 at 14:56
  • @Foobyto - No I don't. Worth adding a new question to get it answered. – Java42 Mar 23 '12 at 16:57
  • Actually, after research, you can't write in RAM with java, you need to do it through the system api. This thing for exemple: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366537 Java just let you to put a file in RAM in order to modify it faster, that's all. – Foobyto Apr 05 '12 at 14:37
0

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().

prunge
  • 22,460
  • 3
  • 73
  • 80