Search code examples
javaftpinputstreamskipbufferedinputstream

How to resume reading an InputStream using the FTP protocol


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?


Solution

  • 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.