问题描述
是否有Java方法可以为应用程序中的独占用途预先分配驱动器空间?
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 existing filesystem (so could easily be a database), but it should allow for reserving the specified amount of space and allow for random reads/writes with high enough throughput.
推荐答案
您可以尝试使用RandomAccessFile对象并使用setLength()方法.
You could try using a RandomAccessFile object and use the setLength() method.
示例:
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...
}
}
}
注意:在创建RandomAccessFile对象之前,该文件必须存在.
Note: The file must exist before you create the RandomAccessFile object.
然后可以使用RandomAccessFile对象读取/写入文件.确保目标文件系统具有足够的可用空间.每个空格可能不是排他性"的,但您始终可以使用文件锁来做到这一点.
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:如果最终意识到硬盘驱动器缓慢且无用(或者从一开始就打算使用RAM),则可以使用java.nio中的ByteBuffer对象. allocate()和allocateDirect()方法应该绰绰有余.字节缓冲区将分配到RAM(以及可能的SwapFile)中,并且是此Java程序专有的.可以通过更改缓冲区的位置来进行随机访问.由于这些缓冲区使用带符号的整数作为参考位置,因此最大大小限制为2 ^ 31-1.
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.
有关RandomAccessFile的更多信息,请此处.
Read more on RandomAccessFile here.
详细了解FileLock(java对象)这里.
Read more on FileLock (the java object) here.
有关ByteBuffer的更多信息,请参见此处.
Read more on ByteBuffer here.
这篇关于预先分配驱动器空间用于文件存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!