Cannot download file from URL in java -


i'm making program download files url. downloading starts, not completed. example, if file's size 3 mb, program download half of cannot open downloaded file. program says file downloaded succesfully.

public class filedownloader {      public static void main (string [] args) throws ioexception {          inputstream filein;         fileoutputstream fileout;         scanner s = new scanner(system.in);          system.out.println("enter url: ");         string urlstr = s.nextline();          url url = new url(urlstr);         urlconnection urlconnect = url.openconnection();         filein = urlconnect.getinputstream();          system.out.println("enter file name: ");         string filestr = s.nextline();         fileout = new fileoutputstream(filestr);          while (filein.read() != -1) {                fileout.write(filein.read());         }         system.out.println("file downloaded");     } } 

so how can solve it? should use way download?

you losing every alternate bytedue to

    while (filein.read() != -1) {     //1st read         fileout.write(filein.read());     //2nd read - 1st write     } 

you reading twice , writing once.

what need

    int x;     while ((x = filein.read()) != -1) {   //1st read         fileout.write(x);     //1st write     } 

here complete code

import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.net.url; import java.net.urlconnection; import java.util.scanner;  public class filedownloader {      public static void main(string[] args) throws ioexception {          inputstream filein;         fileoutputstream fileout;         scanner s = new scanner(system.in);          system.out.println("enter url: ");         string urlstr = s.nextline();          url url = new url(urlstr);         urlconnection urlconnect = url.openconnection();         filein = urlconnect.getinputstream();          system.out.println("enter file name: ");         string filestr = s.nextline();         fileout = new fileoutputstream(filestr);          int x;         while ((x = filein.read()) != -1) {             fileout.write(x);         }         system.out.println("file downloaded");  } 

Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -