Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

skip() with InputStream

 
Nicolas Viollin
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keep in mind that skipped bytes are still transferred over the stream.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic