我想写一个来自网络的文件,所以我不知道正在进入的文件的大小。有时文件服务器上的磁盘可能会被填满,我想要回复一条消息我的客户通知他们这个错误。我找不到任何能够捕获此类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()
失败因为磁盘已满了吗?
答案 0 :(得分:1)
即使不建议解析错误消息,您也可以这样做:
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在您编写之前检查您是否有足够的空间(如果您使用的是共享文件夹或多线程,则不够软件)