Pre-allocating drive space for file storage

后端 未结 4 1053
挽巷
挽巷 2021-02-06 11:39

Is there a Java way to pre-allocate drive space for exclusive usage in the application?

There is no requirement for this space to be a separate filesystem or a part of

4条回答
  •  一个人的身影
    2021-02-06 12:22

    You could try using a RandomAccessFile object and use the setLength() method.

    Example:

    File file = ... //Create a temporary file on the filesystem your trying to reserve.
    long bytes = ... //number of bytes you want to reserve.
    
    RandomAccessFile rf = null;
    try{
        rf = new RandomAccessFile(file, "rw"); //rw stands for open in read/write mode.
        rf.setLength(bytes); //This will cause java to "reserve" memory for your application by inflating/truncating the file to the specific size.
    
        //Do whatever you want with the space here...
    }catch(IOException ex){
        //Handle this...
    }finally{
        if(rf != null){
            try{
                rf.close(); //Lets be nice and tidy here.
            }catch(IOException ioex){
                //Handle this if you want...
            }
        }
    }
    

    Note: The file must exist before you create the RandomAccessFile object.

    The RandomAccessFile object can then be used to read/write to the file. Make sure the target filesystem has enough free space. The space may not be "exclusive" per-say but you can always use File Locks to do that.

    P.S: If you end up realizing hard drives are slow and useless (or meant to use RAM from the start) you can use the ByteBuffer object from java.nio. The allocate() and allocateDirect() methods should be more than enough. The byte buffer will be allocated into RAM (and possible SwapFile) and will be exclusive to this java program. Random access can be done by changing the position of the buffer. Since these buffers use signed integers to reference position, max sizes are limited to 2^31 - 1.

    Read more on RandomAccessFile here.

    Read more on FileLock (the java object) here.

    Read more on ByteBuffer here.

提交回复
热议问题