Java中为多个文件下载分配磁盘空间
有没有办法通过“标准”Java(J2SE 5 或更高版本)可靠地“分配”(保留)硬盘空间?
以多线程应用程序为例,在线程池中执行,其中每个线程都下载文件。应用程序如何确保其下载不会因磁盘空间耗尽而中断?
至少,如果它事先知道正在下载的文件的大小,它是否可以进行某种“保留”,这将保证文件下载,而不管其他线程在做什么?
(StackOverflow中有一个类似问题,但它没有讨论多线程并且还使用 NIO。)
编辑:经过一些进一步的测试,针对类似问题提出的解决方案似乎不起作用,因为可以通过建议的 RandomAccessFile 方法设置任何允许的长度,而不管潜在的硬盘空间。例如,在只有几 GB 可用空间的分区上,我能够随意创建 TB(太字节!) 文件。
如果 File 类的 getFreeSpace() 方法在每次创建新文件时报告可用空间量减少,则该解决方案就足够了,但实际上并没有,从而确认了在实践中这些文件的长度为零似乎有。
这些至少是我在运行 VMWare Player 4.0.0 的 CentOS 5.6 虚拟机上看到的结果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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.