日期:2014-05-20  浏览次数:20821 次

java File 类中的 mkdirs 问题。(剩余空间不足以建立目录,怎么检测出来呢?)
局部代码如下:
File directory = new File(directoryName);
  if (!directory.isDirectory()) {
  if (!directory.mkdirs()) {
.........................
这个地方,mkdirs只能返回 true 和 false. 但是貌似不抛出IO异常, 当磁盘空间满的时候,就会发生创建失败的原因(创建dir大概需要30k左右的空间,当磁盘完全满了,就创建不出来了。)

想到一个通过检测磁盘空间的方法,来检测是否是磁盘满了导致的 mkdirs创建失败,但是这样做感觉不够严谨。 

各位高手,请问一下,有没有这样的 API :创建目录 ,失败后可以抛出相关的异常(IO异常,根据异常信息可以判断是否是空间不足导致的。) 

请各位高手帮帮忙。

------解决方案--------------------
File类有一个方法可以得到剩余的空间,不知道能不能满足你的需求。

getFreeSpace

public long getFreeSpace()

Returns the number of unallocated bytes in the partition named by this abstract path name.

The returned number of unallocated bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.
------解决方案--------------------
探讨
不好意思,标题写的有些失误。 目前我可以获取磁盘的剩余空间,使用剩余空间小于某个值的方法。 但是感觉这个方法有些不妥。 不够严谨,想寻求更好的方法。

------解决方案--------------------
如果有多线程的话,确实不严谨,加锁~~用FileChannel.tryLock()方法
------解决方案--------------------
我觉得你完全可以不用考虑这个情况,如果你程序放在服务器上,你服务器的空间必须足够大,如果你是存电影或者其它的大文件的话,你必须保证你服务器足够大,当你服务器上的空间不够的时候,其实你可以写个脚本,当服务器的空间缩小到一定程序时,将一些日志文件或其它文件移动到其它的目录下,也就是说,你完全可以不用考虑mkdir会存在空间不够的情况,

当然你只想在本地做测试,来完成这个的话,觉得在异常信息里处理比较好