GeeCON Prague 2014*
The moose likes I/O and Streams and the fly likes skip() with InputStream Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "skip() with InputStream" Watch "skip() with InputStream" New topic
Author

skip() with InputStream

Nicolas Viollin
Greenhorn

Joined: Apr 13, 2001
Posts: 26
Hello,


I would like to know if there's an effective way to skip already read bytes from an InputStream ??
I would like to write a program which allows to resume downloads.


Here is the code I use

private void doSkip(RandomAccessFile raf, InputStream is){
try{
long toSkip = raf.length();
long count = 0;
long skip = toSkip;
long effectiveskip = 0;

while (count != toSkip){
effectiveskip = is.skip(skip);
count += effectiveskip;
skip = (toSkip - count);
System.out.println("Skiping " + effectiveskip);
}
}catch(Exception e){
e.printStackTrace();
}
}

public void run(){
try{
URLConnection uc = _url.openConnection();
InputStream is = uc.getInputStream();
RandomAccessFile raf = new RandomAccessFile(_url.getFile(), "rw");

int i = 0; byte[] buff = new byte[4096];
long count = 0;
long start = System.currentTimeMillis();
if (raf.length() > 0){
raf.seek(raf.length());
doSkip(raf, is);
}
long elapsedtime = 0;
long dlspeed = 0;
long dlspeedsum = 0;
int iteration = 0;
while ((i = is.read(buff)) != -1){
raf.write(buff, 0, i);
count += i;
//System.out.println("Copied: " + count + " bytes");
//Thread.sleep(60);
elapsedtime = (System.currentTimeMillis() - start) / 1000;
if (elapsedtime > 0){
dlspeed = (count >> 10) / elapsedtime;
dlspeedsum += dlspeed;
}
iteration++;
}
System.out.println("Vitesse de DL moyenne: " + dlspeedsum / iteration);
is.close();
raf.close();
}catch(Exception e){
e.printStackTrace();
}
}


thnx
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Keep in mind that skipped bytes are still transferred over the stream.
 
jQuery in Action, 2nd edition
 
subject: skip() with InputStream