download Package - Android App

Android examples for App:Package

Description

download Package

Demo Code


//package com.java2s;

import java.io.File;
import java.io.FileOutputStream;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Environment;
import android.util.Log;

public class Main {

    public static String fileDir = Environment
            .getExternalStorageDirectory().getPath() + "/appControl/";

    public static String downloadPackage(String packageUrl)
            throws Exception {
        String[] tmpStrings = packageUrl.split("/");
        String filePath = fileDir + tmpStrings[tmpStrings.length - 1];
        Log.i("yangtong", "filePath >>" + filePath);
        if (!new File(fileDir).exists()) {
            Log.i("yangtong", "!new File(fileDir).exists()");
            new File(fileDir).mkdir();
        }/*from ww  w  . j av a 2 s .  c  o  m*/
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        URL url = new URL(packageUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        OutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        outputStream.flush();
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
        return filePath;
    }
}

Related Tutorials