-1

when I am trying to download files from server, it misses some bytes! and shows as a corrupted file. below the code i tried to download from URL. It gives no exception while running. I am using this in a service. these are the sample results from my tries:

file 1: actual size = 73.2 kb downloaded size = 68.7 kb

file 2: actual size = 147 kb downloaded size = 137 kb

file 3: actual size = 125 kb downloaded size = 116.8 kb

please help me to find the correction needed to my code. thanks,

    InputStream stream = null;
    FileOutputStream fos = null;
    try {

        URL url = new URL(urlPath);
        stream = url.openConnection().getInputStream();
        InputStreamReader reader = new InputStreamReader(stream);
        fos = new FileOutputStream(output.getPath());
        int next = -1;
        while ((next = reader.read()) != -1) {
            fos.write(next);

        }
        // Successful finished
        Log.d("reaching", "reaching : DOWNLOAD FINISHED SUCCESSFULLY");

    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
Blue_Alien
  • 2,148
  • 2
  • 25
  • 29
  • Don't use a `Reader` unless you know the source is text, and if it is you should be using a `Writer` to write it. Otherwise you should be using input and output streams. – user207421 Oct 21 '14 at 11:54
  • thanks @EJP for help, it works when I changed to input and outputStream – Blue_Alien Oct 21 '14 at 13:06

1 Answers1

0

yes, the problem was with the use of InputstreamReader I used InputStream instead of that as @EJP said. And I modified my code to download file from server

Here I am putting my code for someone who comes to this link. May helpful for them.

 try {

        URL url = new URL(urlPath);
        URLConnection conexion = url.openConnection();
        conexion.connect();

        int lenghtOfFile = conexion.getContentLength();
        Log.d("download", "Lenght of file: " + lenghtOfFile);

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new  FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileName);

        byte data[] = new byte[1024];


        int count= -1;

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
Blue_Alien
  • 2,148
  • 2
  • 25
  • 29