为Java中的多个文件下载分配磁盘空间 [英] Allocate disk space for multiple file downloads in Java

查看:168
本文介绍了为Java中的多个文件下载分配磁盘空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过标准" Java(J2SE 5或更高版本)可靠地分配"(保留)硬盘空间?

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?

((在StackOverflow中有一个类似的问题,但它不讨论多线程,也使用NIO.)

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

经过进一步测试,针对类似问题提出的解决方案似乎不起作用,因为可以通过建议的RandomAccessFile方法设置任何允许的长度,而与基础硬盘空间无关.例如,在只有几GB可用空间的分区上,我能够随意创建TB(terrabyte!)文件.

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.

如果File类的getFreeSpace()方法每次创建一个新文件时报告的可用空间减少,则该解决方案就足够了,但实际上并没有,因此确认了零长度,实际上,这些文件似乎都有.

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.

这些至少是我在运行于VMWare Player 4.0.0的CentOS 5.6虚拟机上看到的结果.

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

推荐答案

将零写入文件.这样可以确保您已经分配了磁盘空间(除非正在使用驱动器压缩或文件的某些其他可变大小的编码).

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.

这篇关于为Java中的多个文件下载分配磁盘空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆