1

我正在学习 Java OOP。我的程序通过 FTP 下载文件。我想在重新启动时继续下载。这是我的代码:

URL urlName = new URL(url);
URLConnection con = urlName.openConnection();
BufferedInputStream in = new BufferedInputStream(con.getInputStream());

int i = 0;
long downloadedSizeKB;
System.out.println("before skip");
long k = in.skip(counter);
System.out.println(k);
byte[] bytesIn = new byte[1024];
while ((i = in.read(bytesIn)) >= 0) {
    if(counter >= alreadyDownloadedBytes) {
        out.write(bytesIn, 0, i);
        downloadedSizeKB = counter/1024;
        downSize.setText(downloadedSizeKB + " KB downloaded...");

        while(isPaused) {
            downSize.setText(downloadedSizeKB + " KB PAUSED");
            Thread.sleep(1000);                     
        }
    }
    counter += i;
}

in.close();

起初我尝试阅读它与先前下载的文件的长度一样多,然后从那时开始继续读写。在继续下载之前读取文件需要太多时间(100MB 需要 1-2 分钟)。之后我意识到有一个跳过方法,但我猜它做同样的事情,因为它需要几乎相同的时间。

有没有更快的方法从文件的特定字节开始读取文件?还是我应该以另一种方式做到这一点?或者这是唯一的方法?

4

2 回答 2

2

您可以使用 apache.commons.net.ftp.FTPClient (在 commons-net.jar 库中)。

您有方法:setRestartOffset(yourOffset),在检索文件之前使用它,文件数据将从指定的偏移量开始。

于 2012-10-17T08:36:12.307 回答
0

I haven't looked up the full details for FTP, but yes, skip on the input stream will just read the bytes already read. What you need to do is tell the server to only send the bytes you don't have yet.

In HTTP and FTP this is the RANGE header. This question has the details of how to do this for FTP.

于 2012-10-17T08:25:17.707 回答