📄 download.java
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package DownloadManager;/** * This class downloads a file from a URL. * @author Liu Yu Yang */import java.io.*;import java.net.*;import java.util.*;import java.io.File;import java.util.logging.Level;import java.util.logging.Logger;class Download extends Observable implements Runnable { // These are the status names. public static final String STATUSES[] = {"Downloading", "Paused", "Complete", "Cancelled", "Error", "Stop" }; // These are the status codes. public static final int DOWNLOADING = 0; public static final int PAUSED = 1; public static final int COMPLETE = 2; public static final int CANCELLED = 3; public static final int ERROR = 4; public static final int STOP = 5; private URL url; // download URL private int fileLength; // size of download in bytes private int downloadedLength; // number of bytes downloaded private int status; // current status of download private File fileOut; private int ThreadNum; //number of threads private HttpURLConnection connection; private String urlFileName; //name part of URL file private String localFileAddress; //address which downloaded file to save private String errorMsg; // error message private String fileName; private String usedTime; private long startTime=0; private long endTime=0; private DownloadThread[] down; /** * Constructs a download. * @param url Url for a downloading file. */ public Download(URL url) { this.url = url; fileLength = -1; downloadedLength = 0; status = DOWNLOADING; ThreadNum = 1; // Begin the download. download(); } /** * Constructs a download. * @param url Url for a downloading file. * @param threadNum Numbers of thread for a downloading file. */ @SuppressWarnings("empty-statement") public Download(URL url, int threadNum, String localFileAddress, String filename) { startTime = System.currentTimeMillis(); this.url = url; fileLength = -1; downloadedLength = 0; status = DOWNLOADING; this.localFileAddress = localFileAddress; this.ThreadNum = threadNum; this.fileName=filename; if (createDirectory(localFileAddress) == false) { System.out.println("Creating dir error!"); errorMsg = "Create directory error!"; status = ERROR; return; }// if(ifFileExist(localFileAddress+"\\"+getFileName()))// {// System.out.println("file is existed!");// errorMsg="File is existed!";// status = ERROR;// JOptionPane.showMessageDialog(null,// errorMsg, "NOTICE", JOptionPane.ERROR_MESSAGE);// return;// } // Begin the download. download(); endTime=System.currentTimeMillis();; } /** @return file name include full path e.g. d:\example.txt */ public String getFullFileName() { return localFileAddress+"\\"+getFileName(); } /** @return file name portion of URL */ public String getFileName() { if(fileName.equalsIgnoreCase("")) { String filename = url.getFile(); urlFileName = filename.substring(filename.lastIndexOf('/') + 1); return urlFileName; }else return fileName; } /** @return this download's size */ public long getSize() { return fileLength; } /** @return time cost */ public String getUsedTime() { usedTime=String.valueOf(endTime-startTime); return usedTime; } /** @return this download's progress */ public float getProgress() { return ((float) downloadedLength / fileLength) * 100; } /** @return this download's status */ public int getStatus() { return status; } /** @return this download's error message, if there is */ public String getErrorMsg() { return errorMsg; } /** pause current job */ public void pause() { status = PAUSED; for(int i=0;i<this.ThreadNum;i++) { down[i].pause(); } stateChanged(); } /** resume current job */ public void resume() { status = DOWNLOADING; for(int i=0;i<this.ThreadNum;i++) { down[i].resume(); } stateChanged(); download(); } /** cancel current job */ public void cancel() { status = CANCELLED; for(int i=0;i<this.ThreadNum;i++) { down[i].cancel(); } stateChanged(); } // Mark this download as having an error. private void error() { status = ERROR; stateChanged(); } /** get this download's detailed information. */ public void getDetails() { printMIME(connection); } /** dispose */ public void close() { try { this.finalize(); } catch (Throwable ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } } // Start or resume downloading. private void download() { Thread thread = new Thread(this); thread.start(); } /** * * @param pathAndFile To check this file whether have already downloaded. * @return true:existed false:inexistance */ private boolean ifFileExist(String filePath) { File file = new File(filePath); if (file.exists()) { return true; } else { return false; } } /** override father's method, to start one download */ public void run() { try { // Open connection to URL. connection = (HttpURLConnection) url.openConnection(); // Specify what portion of file to download. connection.setRequestProperty("Range", "bytes=" + downloadedLength + "-"); // Connect to server. connection.connect(); // Make sure response code is in the 200 range. if (connection.getResponseCode() / 100 != 2) { error(); } // Check for valid content length. int contentLength = connection.getContentLength(); if (contentLength < 1) { error(); } /* Set the size for this download if it hasn't been already set. */ if (fileLength == -1) { fileLength = contentLength; stateChanged(); } //!!!!There should be an method to check the directory's existence. //create file to locate downloading fileOut = new File(localFileAddress, getFileName()); //run threads down = new DownloadThread[ThreadNum]; for (int i = 0; i < ThreadNum; i++) { RandomAccessFile file = new RandomAccessFile(fileOut, "rw"); file.setLength(fileLength); long block = fileLength / ThreadNum + 1; file.seek(block * i); down[i] = new DownloadThread(url, file, block, i + 1); //down[i] } boolean flag = true; while (flag) { Thread.sleep(500); flag = false; for (int i = 0; i < ThreadNum; i++) { if (!down[i].isFinished()) { flag = true; break; } } }// end while System.out.println("File is downloaded locating at " + fileOut.getPath()); /* Change status to complete if this point was reached because downloading has finished. */ if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (IOException ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } this.downloadedLength=this.fileLength; } /** * Show downloading file's MIME information by its http * @param http Type:HttpURLConnection */ private void printMIME(HttpURLConnection http) { for (int i = 0;; i++) { String mine = http.getHeaderField(i); if (mine == null) { return; } System.out.println(http.getHeaderFieldKey(i) + ":" + mine); } } /** * @localFileAddress path of file which is going to save * this method return false when the directory is existed, * return true when the directory is not existed and creating the directory */ public boolean createDirectory(String localFileAddress) { File file = new File(localFileAddress); if (!file.exists()) { try { file.mkdir(); System.out.println("folder created"); } catch (Exception e) { System.out.println("folder can not created"); return false; } } return true; } // Notify observers that this download's status has changed. private void stateChanged() { setChanged(); notifyObservers(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -