Pergunta

I am learning Java OOP. My program downloads file via FTP. I want to resume downloading when it is started again. Here is my code :

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();

At first I've tried reading it as much as the lenght of previously downloaded file and then resume reading and writing from that point. Reading file before resuming downloading takes too much time (1-2 minutes for like 100MB). After that I realized there is a skip method but I guess it does the same thing since it takes nearly same amount of time.

Is there faster way to start reading a file from a specific byte of it? Or should I do this some another way? Or this is the only way?

Foi útil?

Solução

You can use apache.commons.net.ftp.FTPClient (is in commons-net.jar library).

You have methods as: setRestartOffset(yourOffset), using it before retrieve the file, the file data will start from the specified offset.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top