首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中判断循环沿InputStream的距离

如何在Java中判断循环沿InputStream的距离
EN

Stack Overflow用户
提问于 2011-11-22 19:54:49
回答 2查看 141关注 0票数 0

我正在尝试做一个下载程序,这样我就可以自动更新我的程序了。到目前为止,我的代码如下:

代码语言:javascript
复制
  public void applyUpdate(final CharSequence ver)
  {
    java.io.InputStream is;
    java.io.BufferedWriter bw;
    try
    {
      String s, ver;
      alertOf(s);
      updateDialogProgressBar.setIndeterminate(true);//This is a javax.swing.JProgressBar which is configured beforehand, and is displayed to the user in an update dialog
      is = latestUpdURL.openStream();//This is a java.net.URL which is configured beforehand, and contains the path to a replacement JAR file
      bw = new java.io.BufferedWriter(new java.io.FileWriter(new java.io.File(System.getProperty("user.dir") + java.io.File.separatorChar + TITLE + ver + ".jar")));//Creates a new buffered writer which writes to a file adjacent to the JAR being run, whose name is the title of the application, then a space, then the version number of the update, then ".jar"
      updateDialogProgressBar.setValue(0);
      //updateDialogProgressBar.setMaximum(totalSize);//This is where I would input the total number of bytes in the target file
      updateDialogProgressBar.setIndeterminate(false);
      {
        for (int i, prog=0; (i = is.read()) != -1; prog++)
        {
          bw.write(i);
          updateDialogProgressBar.setValue(prog);
        }
        bw.close();
        is.close();
      }
    }
    catch (Throwable t)
    {
      //Alert the user of a problem
    }
  }

正如您所看到的,我只是尝试用进度条制作一个下载程序,但是我不知道如何告诉目标文件的总大小。如何知道在文件下载之前要下载多少字节?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-11-22 20:07:49

一个流是一个字节流,你不能问它还有多少字节,你只需要从它读取,直到它说‘我完成’。现在,根据提供流的连接是如何建立的,可能底层协议(例如HTTP)可以预先知道要发送的总长度.也许不是。有关此问题,请参见URLConnection.getContentLength()。但它很可能会回来-1 (‘我不知道’)。

顺便说一句,您的代码不是读取字节流并将其写入文件的适当方式。首先,您使用的是Writer,而您应该使用OutputStream (您正在将字节转换为字符,然后再转换为字节--这会影响性能,如果接收的内容是二进制的,或者编码不匹配,则可能会破坏一切)。第二,一次读写一个字节的效率很低。

票数 3
EN

Stack Overflow用户

发布于 2011-11-22 20:13:07

要获取文件的长度,可以执行以下操作:

代码语言:javascript
复制
new File("System.getProperty("user.dir") + java.io.File.separatorChar + TITLE + ver + ".jar").length()
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8232912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档