Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

Download a file programmatically on Android

I am downloading files from web server programmatically. After download is completed, I checked the file. The size ,extension and all other parameters are correct but when I try to play that file in media player it is showing that it is corrupted.

Here is my 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...