gpt4 book ai didi

java - 在用java编写时限制文件大小

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:20 25 4
gpt4 key购买 nike

我需要将文件大小限制为 1 GB,同时最好使用 BufferedWriter 进行写入。

是否可以使用 BufferedWriter 或者我必须使用其他库?

喜欢

try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
//...
writer.write(lines.stream());
}

最佳答案

您始终可以编写自己的 OutputStream 来限制写入的字节数

以下假定您希望在超出大小时抛出异常。

public final class LimitedOutputStream extends FilterOutputStream {
private final long maxBytes;
private long bytesWritten;
public LimitedOutputStream(OutputStream out, long maxBytes) {
super(out);
this.maxBytes = maxBytes;
}
@Override
public void write(int b) throws IOException {
ensureCapacity(1);
super.write(b);
}
@Override
public void write(byte[] b) throws IOException {
ensureCapacity(b.length);
super.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
ensureCapacity(len);
super.write(b, off, len);
}
private void ensureCapacity(int len) throws IOException {
long newBytesWritten = this.bytesWritten + len;
if (newBytesWritten > this.maxBytes)
throw new IOException("File size exceeded: " + newBytesWritten + " > " + this.maxBytes);
this.bytesWritten = newBytesWritten;
}
}

当然,您现在必须手动设置 Writer/OutputStream 链。

final long SIZE_1GB = 1073741824L;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new LimitedOutputStream(Files.newOutputStream(path), SIZE_1GB),
StandardCharsets.UTF_8))) {
//
}

关于java - 在用java编写时限制文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39092861/

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