Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot download file from URL in java

I'm making a program that will download files from URL. The downloading always starts, but it is not completed. For example, if file's size is 3 MB, program download only half of that so I cannot open the downloaded file. But program says that file is 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 is downloaded");
    }
}

So how can I solve it? Should use another way to download?

like image 614
Azamat Salamat Avatar asked Jul 13 '15 18:07

Azamat Salamat


1 Answers

You are losing every alternate bytedue to

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

You are reading twice and writing only once.

What you need to do is

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

Here is your 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 is downloaded");

}
like image 184
Shrinivas Shukla Avatar answered Sep 30 '22 03:09

Shrinivas Shukla