Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an in-memory File object in Java?

Tags:

java

One of the optimization projects I'm working on right now makes extensive use of EPANet. We make repeated calls to two simulation methods in EPANet to understand how water flows through a water distribution network.

HydraulicSim is one of the classes we make use of. See the overloaded simulate methods:

public void simulate(File hyd) throws ENException {
    ...
}

public void simulate(OutputStream out) throws ENException, IOException {
    ...
}

public void simulate(DataOutput out) throws ENException, IOException {
    ...
}

The other class we use is QualitySim. Here, we also use the overloaded simulate methods:

public void simulate(File hydFile, File qualFile) throws IOException, ENException {
    ...
}

void simulate(File hydFile, OutputStream out) throws IOException, ENException {
    ...
}

Here's what we're currently doing:

  1. Create two File objects, hydFile and qualFile.
  2. Call HydraulicSim.simulate on hydFile.
  3. Call QualitySim.simulate on hydFile and qualFile.
  4. Delete the files.

The problem is that we have to do this a lot of times. For a large problem, we can do this hundreds of thousands or even millions of times. You can imagine the slowdown repeatedly creating/writing/deleting these files causes.

So my question is this: Is it possible for me to create these files so that they reside only in memory and never touch the disk? Each file is very small (I'm talking a few hundred bytes), so throwing them into memory won't be a problem; I just need to figure out how. I searched around and didn't really find much, save for MappedByteBuffer, but I'm not sure how, or if it's even possible, to create a File from that class.

Any advice is welcome!

like image 992
Geoff Avatar asked Mar 10 '14 17:03

Geoff


People also ask

How do you create a new file object in Java?

Example 1: Java Program to Create a File java is equivalent to // currentdirectory/JavaFile. java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.

Which method is used to create the file in Java?

To create a new file, you need to use File. createNewFile() method. This method returns a boolean value: true if the file is accomplished.


1 Answers

The most straightforward solution is to mount ramdisk and store file here. Then you do not need to touch your code and file access will be lightning fast :-)

Linux

# mkfs -q /dev/ram1 8192
# mkdir -p /ramcache
# mount /dev/ram1 /ramcache

MacOS

  1. http://osxdaily.com/2007/03/23/create-a-ram-disk-in-mac-os-x/

Windows

  1. http://support.microsoft.com/kb/257405
  2. http://www.softperfect.com/products/ramdisk/
like image 135
Leos Literak Avatar answered Sep 30 '22 05:09

Leos Literak