我正在尝试做一个下载程序,这样我就可以自动更新我的程序了。到目前为止,我的代码如下:
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
}
}正如您所看到的,我只是尝试用进度条制作一个下载程序,但是我不知道如何告诉目标文件的总大小。如何知道在文件下载之前要下载多少字节?
发布于 2011-11-22 20:07:49
一个流是一个字节流,你不能问它还有多少字节,你只需要从它读取,直到它说‘我完成’。现在,根据提供流的连接是如何建立的,可能底层协议(例如HTTP)可以预先知道要发送的总长度.也许不是。有关此问题,请参见URLConnection.getContentLength()。但它很可能会回来-1 (‘我不知道’)。
顺便说一句,您的代码不是读取字节流并将其写入文件的适当方式。首先,您使用的是Writer,而您应该使用OutputStream (您正在将字节转换为字符,然后再转换为字节--这会影响性能,如果接收的内容是二进制的,或者编码不匹配,则可能会破坏一切)。第二,一次读写一个字节的效率很低。
发布于 2011-11-22 20:13:07
要获取文件的长度,可以执行以下操作:
new File("System.getProperty("user.dir") + java.io.File.separatorChar + TITLE + ver + ".jar").length()https://stackoverflow.com/questions/8232912
复制相似问题