Allocate disk space for multiple file downloads in Java

拜拜、爱过 提交于 2019-12-10 11:36:18

问题


Is there any way of reliably "allocating" (reserving) hard disk space via "standard" Java (J2SE 5 or later)?

Take for example the case of a multithreaded application, executing in a thread pool, where every thread downloads files. How can the application make sure that its download won't be interrupted as a result of disk space exhaustion?

At least, if it knows beforehand the size of the file it is downloading, can it do some sort of "reservation", which would guarantee file download, irrespective of what the other threads are doing?

(There is a similar question in StackOverflow, but it does not discuss multithreading and also uses NIO.)

EDIT: After some further testing, the solution proposed on the similar question does not seem to work, as one can set ANY allowed length via the suggested RandomAccessFile approach, irrespective of the underlying hard disk space. For example, on a partition with only a few gigabytes available, I was able to create TB (terrabyte!) files at will.

The solution would have been sufficient if the getFreeSpace() method of the File class reported a decreased amount of available space every time one created a new file, but it actually doesn't, thus confirming the zero length which, in practice, these files seem to have.

These are at least the results I am seeing on a CentOS 5.6 virtual machine, running in VMWare Player 4.0.0.


回答1:


Write zeros to the file. That will ensure you have allocated disk space (unless drive compression or some other variable-size encoding of the file is in use).

You might get away with writing a single zero for every block, but determining the blocksize may not be trivial.

This is to avoid the creation of a sparse file which does not have all your space allocated.



来源:https://stackoverflow.com/questions/7798924/allocate-disk-space-for-multiple-file-downloads-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!