java 限制文件大小_在java中编写时限制文件大小

我需要将文件大小限制为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,file,bufferedwriter

来源: https://codeday.me/bug/20190717/1487779.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值