1.調用
URL url = new URL(DownStatic.murlsString); // 尋找資源服務器
connection = (HttpURLConnection) url.openConnection(); 與服務器建立連接
InputStream is = connection.getInputStream(); 建立資源流
randomAccessFile = new RandomAccessFile(DownStatic.mpathString, "rwd"); 建立本地文件
- public class DownStatic {
- public static String murlsString;
- public static String mpathString;
- private static int compeleteSize; // 完成大小
- public static native void displayProgress(String numString);
- public static native void setFileSize(int pSize);
- public static native void downloadFail();
- public static String downloadAndroid(String pPathString, String pUrlsString) {
- System.out.println("sendWeibo : " + pUrlsString);
- System.out.println("sendWeibo : " + pPathString);
- File fileM = new File(pPathString);
- if (fileM.exists()) {// 如果存在刪除從新下載
- fileM.delete();
- }
- DownStatic.murlsString = pUrlsString;
- DownStatic.mpathString = pPathString;
- DownStatic.down();
- return "";
- }
- public static void down() {
- HttpURLConnection connection = null;
- RandomAccessFile randomAccessFile = null;
- InputStream is = null;
- try {
- URL url = new URL(DownStatic.murlsString);
- connection = (HttpURLConnection) url.openConnection();
- connection.setConnectTimeout(5000); // 5秒
- connection.setRequestMethod("GET");
- DownStatic.setFileSize(connection.getContentLength());
- // 設置範圍,格式爲Range:bytes x-y;
- // connection.setRequestProperty("Range", "bytes="
- // + (0 + 0) + "-" + endPos);
- // randomAccessFile = new RandomAccessFile(localfile, "rwd"); // rwd
- randomAccessFile = new RandomAccessFile(DownStatic.mpathString,
- "rwd");
- // 數據同步讀寫
- // randomAccessFile.seek(startPos + compeleteSize);
- // 將要下載的文件寫到保存在保存路徑下的文件中
- is = connection.getInputStream();
- byte[] buffer = new byte[4096]; // 每次寫入字節數
- int length = -1;
- String string;
- // 不斷下載
- while ((length = is.read(buffer)) != -1) {
- randomAccessFile.write(buffer, 0, length);
- DownStatic.compeleteSize += length;
- string = String.valueOf(DownStatic.compeleteSize);
- DownStatic.displayProgress(string);
- }
- } catch (Exception e) {// 下載失敗
- System.out.println("Exception e Exception e");
- DownStatic.downloadFail();
- e.printStackTrace();
- } finally {
- try {
- is.close();
- randomAccessFile.close();
- connection.disconnect();
- } catch (Exception e) {
- System.out.println("finally finally e Exception e");
- e.printStackTrace();
- }
- }
- }
- }