tags:

views:

566

answers:

3

hi. i am downloading files from web server programatically. after download is complete, i checked the file.the size ,extension and all other parameters are correct but i when i try to play that file in media player it is showing that it is corrupt.

plz help..

code:

byte[] b = null;
InputStream in = null;
b = new byte[Integer.parseInt(size)];    // size of the file.
in = OpenHttpConnection(URL);            
in.read(b);
in.close();

File folder = new File("/sdcard", "folder");

boolean check = folder.mkdirs();

Log.d("HttpDownload", "check " + check);

File myFile = new File("/sdcard/folder/" + name);

myFile.createNewFile();

OutputStream filoutputStream = new FileOutputStream(myFile);

filoutputStream.write(b);

filoutputStream.flush();

filoutputStream.close();

A: 

I checked this stackoverflow question but it looks like there is not a download Intent.

Did you try setting the WRITE_EXTERNAL_STORAGE in the android manifest?

Macarse
A: 

read on an input stream doesn't guarntee that the entire contents of the file will be pulled down in one go. Check the return value on that in.read(b); line. It might look something like this:

if(in.read(b) != size)
    Log.e("Network","Failed to read all data!");

That'll tell you, at the very least, if you're getting all your data from the networking layer. If you only got a partial read, but you're still writing the full byte array to disk, that might explain why the media player thinks the file is corrupt.

haseman
+1  A: 

This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.

private static void downloadFile(String url, File outputFile) {
  try {
      URL u = new URL(url);
      URLConnection conn = u.openConnection();
      int contentLength = conn.getContentLength();

      DataInputStream stream = new DataInputStream(u.openStream());

        byte[] buffer = new byte[contentLength];
        stream.readFully(buffer);
        stream.close();

        DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
        fos.write(buffer);
        fos.flush();
        fos.close();
  } catch(FileNotFoundException e) {
      return; // swallow a 404
  } catch (IOException e) {
      return; // swallow a 404
  }
}
Klondike