转自:http://hold-on.iteye.com/blog/1017449

如果用inputStream对象的available()方法获取流中可读取的数据大小,通常我们调用这个函数是在下载文件或者对文件进行其他处理时获取文件的总大小。

以前在我们初学File和inputStream和outputStream时,有需要将文件从一个文件夹复制到另一个文件夹中,这时候我们用的就是inputStream.available()来获取文件的总大小,而且屡试不爽。

但是当我们要从网络URL中下载一个文件时,我们发现得到的数值并不是需要下载的文件的总大小。

好吧。我们看看JDK文档中怎么解释。

available

public int available()
throws IOException

返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数。下一个调用可能是同一个线程,也可能是另一个线程。一次读取或跳过此估计数个字节不会受阻塞,但读取或跳过的字节数可能小于该数。

注意,有些 InputStream 的实现将返回流中的字节总数,但也有很多实现不会这样做。试图使用此方法的返回值分配缓冲区,以保存此流所有数据的做法是不正确的。

如果已经调用 close() 方法关闭了此输入流,那么此方法的子类实现可以选择抛出 IOException

类 InputStream 的 available 方法总是返回 0

此方法应该由子类重写。

返回:可以不受阻塞地从此输入流读取(或跳过)的估计字节数;如果到达输入流末尾,则返回 0抛出:IOException - 如果发生 I/O 错误。

inputStream 源代码

  1. /**
  2. * Returns the number of bytes that are available before this stream will
  3. * block. This implementation always returns 0. Subclasses should override
  4. * and indicate the correct number of bytes available.
  5. *
  6. * @return the number of bytes available before blocking.
  7. * @throws IOException
  8. *             if an error occurs in this stream.
  9. * @since Android 1.0
  10. */
  11. <span style="color: #ff0000;"> public int available() throws IOException {
  12. return 0;
  13. }</span>

这里返回的是 0 值。

所以说要从网络中下载文件时,我们知道网络是不稳定的,也就是说网络下载时,read()方法是阻塞的,说明这时我们用

inputStream.available()获取不到文件的总大小。

但是从本地拷贝文件时,我们用的是FileInputStream.available(),难道它是将先将硬盘中的数据先全部读入流中?

然后才根据此方法得到文件的总大小?

好吧,我们来看看FileInputStream源代码吧

  1. /**
  2. * Returns the number of bytes that are available before this stream will
  3. * block. This method always returns the size of the file minus the current
  4. * position.
  5. *
  6. * @return the number of bytes available before blocking.
  7. * @throws IOException
  8. *             if an error occurs in this stream.
  9. * @since Android 1.0
  10. */
  11. @Override
  12. public int available() throws IOException {
  13. openCheck();
  14. // BEGIN android-added
  15. // Android always uses the ioctl() method of determining bytes
  16. // available. See the long discussion in
  17. // org_apache_harmony_luni_platform_OSFileSystem.cpp about its
  18. // use.
  19. <span style="color: #ff0000;">return fileSystem.ioctlAvailable(fd.descriptor);</span>
  20. // END android-added
  21. // BEGIN android-deleted
  22. // synchronized (repositioningLock) {
  23. //     // stdin requires special handling
  24. //     if (fd == FileDescriptor.in) {
  25. //         return (int) fileSystem.ttyAvailable();
  26. //     }
  27. //
  28. //     long currentPosition = fileSystem.seek(fd.descriptor, 0L,
  29. //             IFileSystem.SEEK_CUR);
  30. //     long endOfFilePosition = fileSystem.seek(fd.descriptor, 0L,
  31. //             IFileSystem.SEEK_END);
  32. //     fileSystem.seek(fd.descriptor, currentPosition,
  33. //             IFileSystem.SEEK_SET);
  34. //     return (int) (endOfFilePosition - currentPosition);
  35. // }
  36. // END android-deleted
  37. }

这里重写了inputStream中的available()方法

关键是:fileSystem.ioctlAvailable(fd.descriptor);

调用了FileSystem这是java没有公开的一个类,JavaDoc API没有。
其中

fileSystem 是一个IFileSystem对象,IFileSySTEM是java没有公开的一个类,JavaDoc API中没有;

fd是一个FileDescriptor对象,即文件描述符

说明这句代码应该是通过文件描述符获取文件的总大小,而并不是事先将磁盘上的文件数据全部读入流中,再获取文件总大小

搞清楚了这些,但是我们的主要问题没有解决,怎么获得网络文件的总大小?

我想原理应该都差不多,应该也是通过一个类似文件描述符的东西来获取。

网络下载获取文件总大小的代码:

  1. <span style="color: #ff0000;">HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
  2. httpconn.getContentLength();</span>

我们再来看看httpconn.getContentLength();

  1. /**
  2. * Gets the content length in bytes specified by the response header field
  3. * {@code content-length} or {@code -1} if this field is not set.
  4. *
  5. * @return the value of the response header field {@code content-length}.
  6. * @since Android 1.0
  7. */
  8. public int getContentLength() {
  9. <span style="color: #ff0000;">return getHeaderFieldInt("Content-Length", -1);</span> //$NON-NLS-1$
  10. }

关键:getHeaderFieldInt("Content-Length", -1);

意思是从http预解析头中获取“Content-length”字段的值

其实也是类似从文件描述符中获取文件的总大小

(判断url文件大小)关于inputStream.available()方法获取下载文件的总大小的更多相关文章

  1. [Android Pro] 关于inputStream.available()方法获取文件的总大小

    reference to :http://hold-on.iteye.com/blog/1017449 如果用inputStream对象的available()方法获取流中可读取的数据大小,通常我们调 ...

  2. PHP学习笔记,curl,file_get_content,include和fopen四种方法获取远程文件速度测试.

    这几天在做抓取.发现用PHP的file_get_contents函数来获取远程文件的过程中总是出现失败,并且效率很低下.所以就做了个测试的demo来测试下PHP中各种方法获取文件的速度. 程序里面使用 ...

  3. fileInputStream.available()获取 文件的总大小

    available():返回与之关联的文件的字节数 我们用inputStream.available()获取 文件的总大小

  4. 获取文件夹总大小方法2_获取cmd命令结果,效率最高

    public static long GetDirectorySize(string path) { long res = 0; System.Diagnostics.Process p = new ...

  5. axios 如何获取下载文件的进度条

    exportFun(){         let _that = this         const instance = this.axios.create({           onDownl ...

  6. 获取sd卡的总大小和可用大小

  7. python 获取指定文件夹的大小

    def getdirsize(dirpath): size = for root, dirs, files in os.walk(dirpath): size += sum([getsize(join ...

  8. Java中获取资源文件的方法总结

    这里总结3中方法获取资源文件的 ServletContext Class ClassLoader 文件的位置 1. ServletContext public void doGet(HttpServl ...

  9. Javaweb向服务器上传文件以及从服务器下载文件的方法

    先导入jar包 点击下载 commons-fileupload是Apache开发的一款专门用来处理上传的工具,它的作用就是可以从request对象中解析出,用户发送的请求参数和上传文件的流. comm ...

随机推荐

  1. MAC Pro 2017款 无线上网慢

    MAC Pro 2017款 在无线路由器和MAC相隔一个房间,上网很慢,怀疑是无线路由器有问题,但其他几台老款MAC和PC上网正常.后来将蓝牙关掉,上网就很快了.

  2. python_day7学习笔记

    类 1)创建一个类 #coding=utf-8 __author__ = 'Administrator' class Employee: '所有员工的基类' empCount = 0 def __in ...

  3. LightOJ - 1370

    Bi-shoe and Phi-shoe Time Limit: 2000MS   Memory Limit: 32768KB   64bit IO Format: %lld & %llu S ...

  4. Hive分组取第一条记录

    需求 交易系统,财务要求维护每个用户首个交易完成的订单数据(首单表,可取每个用户交易完成时间最老的订单数据).举例: 简写版的表结构: 表数据: 则 财务希望汇总记录如下: uid order_id ...

  5. Python3发送qq邮件,测试通过

    import smtplib from email.mime.text import MIMEText # 收件人列表 mail_namelist = ["10402852@qq.com&q ...

  6. 操作cephfs的基本命令

    [前提是已有一个基本可用的ceph集群] 一,在指定节点上部署mds: ceph-deploy mds create ceph-node1 二,新建两个存储池,用于保存cephfs的数据和元数据. c ...

  7. QT库在Windows上的编译

    1.从http://www.qtcentre.org/下载QT源代码,注意是源代码.我下载到的是QT4.5.1版,文件名为qt-win-opensource-src-4.5.1.zip: 2.解压,注 ...

  8. 转:Apache+Fastcgi+Django

    07年作者就贴出的文章了,可见多么古老的运行方式还在用. 转:http://www.cnblogs.com/RChen/archive/2007/03/23/django_fcgi.html 首先要安 ...

  9. Codeforces Round #277 (Div. 2) D. Valid Sets (DP DFS 思维)

    D. Valid Sets time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  10. ubuntu的boot分区报警,删除无用内核文件。

    1. 查看当前使用内核:uname -r4.4.0-97-generic 2. 查看安装的内核dpkg --list 'linux-image*' 3. 删除旧内核sudo apt-get remov ...