Java 获取SXSSFWorkbook的文件大小

Java 获取SXSSFWorkbook的文件大小,java,apache-poi,Java,Apache Poi,有没有办法获取由SXSSFWorkbook生成的Excel的大小 我需要检查生成的文件的大小,并根据大小执行不同的操作,例如,如果大小较小,则直接发送电子邮件,如果大小超过某个限制,则上载到某个位置 感谢一个简单的解决方案:您可以将工作簿写入文件,然后分析其大小 Workbook wb = ... try (OutputStream os = new FileOutputStream("sheet.xlsx")) { wb.write(os); } long len = new File

有没有办法获取由SXSSFWorkbook生成的Excel的大小

我需要检查生成的文件的大小,并根据大小执行不同的操作,例如,如果大小较小,则直接发送电子邮件,如果大小超过某个限制,则上载到某个位置


感谢一个简单的解决方案:您可以将
工作簿
写入文件,然后分析其大小

Workbook wb = ...
try (OutputStream os = new FileOutputStream("sheet.xlsx")) {
    wb.write(os);
}
long len = new File("sheet.xlsx").length();
if (len > 1024_1024) {
    // upload
} else {
    // email
}
如果要限制文件大小,并且如果超过此限制则失败,可以使用以下包装器包装
OutputStream

public class LimitingOutputStream extends OutputStream {
    private final OutputStream stream;
    private final long limitInBytes;
    private final AtomicLong bytesWritten = new AtomicLong();

    public LimitingOutputStream(@NotNull OutputStream out, long limitInBytes) {
        stream = out;
        this.limitInBytes = limitInBytes;
    }

    @Override
    public void write(int b) throws IOException {
        increaseCounterAndValidateNotOverflown(1);
        stream.write(b);
    }

    @Override
    public void write(@NotNull byte[] b) throws IOException {
        increaseCounterAndValidateNotOverflown(b.length);
        stream.write(b);
    }

    @Override
    public void write(@NotNull byte[] b, int off, int len) throws IOException {
        increaseCounterAndValidateNotOverflown(len);
        stream.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        stream.flush();
    }

    @Override
    public void close() throws IOException {
        stream.close();
    }

    private void increaseCounterAndValidateNotOverflown(int delta) throws IOException {
        long count = bytesWritten.addAndGet(delta);
        if (count > limitInBytes) {
            throw new IOException(String.format("Output stream overflown; only %d allowed, but tried to write %d bytes", limitInBytes, count));
        }
    }
}
像这样使用它

try (OutputStream os = new LimitingOutputStream(new FileOutputStream("sheet.xlsx"), 1024_1024)) {

为excel文件创建
File
对象,并调用其
length()
方法获取文件中的字节数:
File File=new File(“excel.xls”);file.length()