Write file to memory using java.nio?

Using nio, you can display an existing file in memory. But is it possible to create it only in memory without a file on the hard drive?

I want to emulate the Windows CreateFileMapping functions that allow writing to memory.

Is there an equivalent system in Java?

The goal is to write to memory so that another program (c) reads it.

+6
source share
3 answers

Take a look at the following. The file is created, but it can be as close to yours as possible.

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

Here is a snippet to try to get 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) { ... 
+3
source

By definition, there is a file on disk. Your question embodies a contradiction in terms.

0
source

Most Java libraries have input and output streams , unlike java.io.File objects.
Examples: Image Viewer , XML , Audio , Zip

Whenever possible, use streams when working with I / O.

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

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

0
source

Source: https://habr.com/ru/post/911437/


All Articles