[Android Pro] InputStream.skip方法的思考

参考 : http://blog.csdn.net/gsyzhu/article/details/8102286

在java.io.InputStream类中定义了skip这个方法。在API中的描述如下:

skip

public long skip(long n)
          throws IOException
Skips over and discards  n bytes of data from this input stream. The  skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly  0. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of bytes skipped is returned. If  n is negative, no bytes are skipped.

The skip method of this class creates a byte array and then repeatedly reads into it until n bytes have been read or the end of the stream has been reached. Subclasses are encouraged to provide a more efficient implementation of this method. For instance, the implementation may depend on the ability to seek.

 

Parameters:
n - the number of bytes to be skipped.
Returns:
the actual number of bytes skipped.
Throws:
IOException - if the stream does not support seek, or if some other I/O error occurs.

翻译如下:

 skip(long n) throws IOException


跳过和丢弃此输入流中数据的 n 个字节。出于各种原因,skip 方法结束时跳过的字节数可能小于该数,也可能为 0。导致这种情况的原因很多,跳过 n 个字节之前已到达文件末尾只是其中一种可能。返回跳过的实际字节数。如果 n 为负,则不跳过任何字节。

此类的 skip 方法创建一个 byte 数组,然后重复将字节读入其中,直到读够 n 个字节或已到达流末尾为止。建议子类提供此方法更为有效的实现。例如,可依赖搜索能力的实现。

n
要跳过的字节数。
return
跳过的实际字节数。
Throws IOException
如果流不支持搜索,或者发生其他 I/O 错误。

 

同时,其子类FileInputStream中也继承了skip这个方法。如API中所描述的,skip方法会存在跳过的字节数小于预期的情况。如果不对返回值进行处理的话,很容易忽视这个问题,导致结果错误。最近在看baksmali的源码,其中有一个简单而巧妙的方法来避过skip方法的这个弊端。

在分片上传文件的时候,进行skip,该处理手段非常重要。

复制代码
FileInputStream in = new FileInputStream(file);
int at = offset;
while(at > 0) {
     long realSkip = in.skip(at);
     if (realSkip == -1) {
            throw new RuntimeException(file + ": unexpected EOF");
      }
      at -= realSkip;
}
复制代码
分类:  Android Pro, Java基础
本文转自demoblog博客园博客,原文链接http://www.cnblogs.com/0616--ataozhijia/p/4973042.html如需转载请自行联系原作者

demoblog
优秀的个人博客,低调大师

微信关注我们

原文链接:https://yq.aliyun.com/articles/363094

转载内容版权归作者及来源网站所有!

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

相关文章

发表评论

资源下载

更多资源
优质分享Android(本站安卓app)

优质分享Android(本站安卓app)

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario,低调大师唯一一个Java游戏作品

Mario,低调大师唯一一个Java游戏作品

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Apache Tomcat7、8、9(Java Web服务器)

Apache Tomcat7、8、9(Java Web服务器)

Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。

Java Development Kit(Java开发工具)

Java Development Kit(Java开发工具)

JDK是 Java 语言的软件开发工具包,主要用于移动设备、嵌入式设备上的java应用程序。JDK是整个java开发的核心,它包含了JAVA的运行环境(JVM+Java系统类库)和JAVA工具。