gpt4 book ai didi

java - 获取 SXSSFWorkbook 的文件大小

转载 作者:行者123 更新时间:2023-11-30 02:28:33 28 4
gpt4 key购买 nike

有没有办法获取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)) {

关于java - 获取 SXSSFWorkbook 的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44892314/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com