栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

读取文件的前N个字节作为Java中的InputStream?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

读取文件的前N个字节作为Java中的InputStream?

完整的答案撕裂并替换:

包装a

InputStream
这样相对简单,以限制在发送数据结束之前将要传递的字节数。
FilterInputStream
是针对这种一般性工作的,但是由于您必须重写此 特定 工作的几乎所有方法,因此它会妨碍您的工作。

这是解决方案的粗略做法:

import java.io.IOException;import java.io.InputStream;public class BoundedInputStream extends InputStream {        private final InputStream data;         private long bytesRemaining;        public BoundedInputStream(InputStream data, long maxBytes) {        this.data = data;        bytesRemaining = Math.max(maxBytes, 0);    }    @Override    public int available() throws IOException {        return (int) Math.min(data.available(), bytesRemaining);    }    @Override    public void close() throws IOException {        data.close();    }    @Override    public synchronized void mark(int limit) {        // does nothing    }    @Override    public boolean markSupported() {        return false;    }    @Override    public int read(byte[] buf, int off, int len) throws IOException {        if (bytesRemaining > 0) { int nRead = data.read(         buf, off, (int) Math.min(len, bytesRemaining)); bytesRemaining -= nRead; return nRead;        } else { return -1;        }    }    @Override    public int read(byte[] buf) throws IOException {        return this.read(buf, 0, buf.length);    }    @Override    public synchronized void reset() throws IOException {        throw new IOException("reset() not supported");    }    @Override    public long skip(long n) throws IOException {        long skipped = data.skip(Math.min(n, bytesRemaining));        bytesRemaining -= skipped;        return skipped;    }    @Override    public int read() throws IOException {        if (bytesRemaining > 0) { int c = data.read(); if (c >= 0) {     bytesRemaining -= 1; } return c;        } else { return -1;        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号