簡體   English   中英

使用Java Nio進行寫操作期間如何檢測磁盤已滿?

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

我想寫一個來自網絡的文件,所以我不知道要傳入的文件的大小。有時文件服務器上的磁盤可能已滿,我想向客戶端返回一條消息通知他們這個錯誤。 我找不到任何有關能夠捕獲此類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類中,我們可以執行以下操作:

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

但是如果由於磁盤已滿而this.mFileChannel.write()失敗,是否有拋出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在寫入之前檢查是否有足夠的空間(如果使用共享文件夾或多線程軟件,則空間不足)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM