如何在 Java nio 的写操作期间检测磁盘已满?

How to detect disk full during write operation with Java nio?

我想写一个来自网络的文件,所以我不知道传入的文件的大小。有时文件服务器上的磁盘可能已满,我想 return 给我的客户的一条消息,通知他们这个错误。我找不到任何关于能够捕获此类 i/o 错误的文档。 FileChannel 将字节从内存流式传输到磁盘,因此检测到这一点可能并不容易。保存是异步发生的吗?是否可以检测到磁盘已满?

// Create a new file to write to
RandomAccessFile mFile = new RandomAccessFile(this.mFilePath, "rw");
FileChannel mFileChannel = this.mFile.getChannel();

// wrappedBuffer has my file in it
ByteBuffer wrappedBuffer = ByteBuffer.wrap(fileBuffer);
while(wrappedBuffer.hasRemaining()) {
    bytesWritten += this.mFileChannel.write(wrappedBuffer, this.mBytesProcessed);
}

我在 File class 中想到,我们可以这样做:

// if there is less than 1 mb left on disk
new File(this.mFilePath, "r").getUsableSpace() < 1024; 

但是如果因为磁盘已满而导致 except if this.mFileChannel.write() 失败,是否有办法抛出异常?

即使不建议解析错误消息,您也可以这样做:

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;

public class SmallDisk {

    final static String SMALL_DISK_PATH = "/Volumes/smallDisk";

    final static Pattern NO_SPACE_LEFT = Pattern.compile(": No space left on device$");

    public static void main(String[] args) throws NoSpaceException {
        Path p = Paths.get(SMALL_DISK_PATH);
        FileStore fs = null;
        try {
            fs = Files.getFileStore(p);
            System.out.println(fs.getUsableSpace());
            Path newFile = Paths.get(SMALL_DISK_PATH + "/newFile");
            Files.createFile(newFile);

        } catch (FileSystemException e) {
            //We catch the "No space left on device" from the FileSystemException and propagate it
            if(NO_SPACE_LEFT.matcher(e.getMessage()).find()){
                throw new NoSpaceException("Not enough space");
            }
            //Propagate exception or deal with it here
        } catch (IOException e) {
            //Propagate exception or deal with it here
        }

    }

    public static class NoSpaceException extends IOException{

        public NoSpaceException(String message) {
            super(message);
        }
    }
}

另一种方法,但它不能保证你不会有例外,是在你写之前使用 FileStore 检查你是否足够space(如果你正在使用共享文件夹或多线程软件)