JAVA編寫的斷點續傳小程序

上了一週的課,今天終於能夠休息了,太棒了,今天閒着無聊使用java語言寫了一個斷點續傳的小程序來分享給你們,java

首先要下載個用於網絡請求的框架:我這裏給出地址,是用的Apache的HttpClient:傳送門 解壓出來有這些jar文件,我用紅框標記的是本次須要使用的apache

這個小程序是沒有界面的一個小程序,在概就是和下圖同樣的了,有一個展現磁盤信息的界面,這個界面不是圖型化的哈小程序

聲名:這個小程序由於是在閒置時間寫的因此沒有細緻的寫程序,只是爲了實現功能能, 以爲有用的能夠看下,以爲對本身沒有幫助的能夠略過,不喜勿噴哈網絡

好了,開始寫代碼吧:框架

建立項目這裏就不用說了哈 首先要顯示如上的界面,這個是展現磁盤信息的一個界面ide

 1     /**
 2      * 初始化硬盤
 3      */
 4     private void initDiskInfo() {
 5         System.out.println("\t\t\t磁盤信息展現");
 6         FileSystemView fsv = FileSystemView.getFileSystemView(); // 獲取文件系統的視圖
 7         File[] fs = File.listRoots(); // 獲取到根目錄
 8         System.out.println("===================================================");
 9         System.out.println("磁盤名稱\t\t磁盤總容量\t\t磁盤剩餘容量");
10         System.out.println("===================================================");
11         for (File f : fs) {
12             System.out.println(fsv.getSystemDisplayName(f) + "\t\t" + FormaetFileSize(f.getTotalSpace()) + "\t\t\t"
13                     + FormaetFileSize(f.getFreeSpace()));
14             System.out.println("===================================================");
15         }
16     }
顯示磁盤信息的代碼

上面的代碼裏面調用的一個格式化字節數的一個FormaetFileSize方法,代碼裏面有寫註釋,在家能夠看下函數

 1 /**
 2      * 計算磁盤容量
 3      * @param fileS 傳入的磁盤字節大小
 4      * @return
 5      */
 6     private String FormaetFileSize(long fileS) {
 7         //這裏使用的是DecimalFormat來作的格式化處理,若是感興趣的能夠自百度下,由於這個我在作程序的時候也是自已現百度的
 8         DecimalFormat dFormat = new DecimalFormat("#.00");
 9         String fileSize = "";
10         if (fileS < 1024) {
11             fileSize = dFormat.format((double) fileS) + "B";
12         } else if (fileS < 1048576) {
13             fileSize = dFormat.format((double) fileS / 1024) + "K";
14         } else if (fileS < 1073741824) {
15             fileSize = dFormat.format((double) fileS / 1048576) + "M";
16         } else {
17             fileSize = dFormat.format((double) fileS / 1073741824) + "G";
18         }
19         return fileSize;
20     }
格式化字節數

main方法的啓動方法this

 1 public static void main(String[] args) {
 2         RunStart runStart = new RunStart();
 3         //展現硬盤磁盤信息
 4         runStart.initDiskInfo();
 5         System.out.print("請輸入要寫入文件的磁盤:");
 6         Scanner scanner  = new Scanner(System.in);
 7         String diskName = scanner.next();
 8         System.out.print("請輸入要寫入文件的路徑(例如:download/):");
 9         String pathName = scanner.next();
10         System.out.print("請輸入文件名");
11         String fileNameString = scanner.next();
12         System.out.print("請輸入文件的URL地址:");
13         String urlString = scanner.next();
14         System.out.println("===="+diskName +":"+File.separatorChar +pathName);
15         new Thread(new FileDowload(urlString,diskName,pathName,fileNameString)).start();
16         
17     }
Main方法

進行下載文件的時候我是建立了一個子線程來進行處理的,這裏須要建立一個類,實現Runnable接口,爲何不使用Thread,由於我習慣使用Runnable接口,我給這個類取了一個url

FileDowload的名字。spa

FileDowload的構造函數,構造的參數已寫明

 1 /**
 2      * 
 3      * @param urlPath   網絡文件的url
 4      * @param panFlag   須要寫入磁盤的盤符
 5      * @param panS      保存文件的路徑
 6      * @param fileName  保存的文件名
 7      */
 8     public FileDowload(String urlPath, String panFlag,String panS,String fileName) {
 9         this.urlPath = urlPath;
10         this.PanFlag = panFlag;
11         this.downloadPath = panS;
12         this.fileName_Disk = fileName;
13         System.out.println("URL:" + urlPath + "\n" + "盤符:"+panFlag+"\n"+"路徑:" + panS +"\n文件名:"+fileName);
14     }
FileDowload構造函數

判斷磁盤空間是否知足

 1 /**
 2      * 判斷磁盤容量是否知足
 3      * @throws IOException 
 4      * @throws ClientProtocolException 
 5      */
 6     private boolean panDiskSize() throws ClientProtocolException, IOException {
 7         //getFreeSpace是獲取到磁盤的剩餘空間
 8         File file =new File(PanFlag + ":");
 9         System.out.println(file.getFreeSpace());
10         HttpClient client = HttpClients.createDefault();
11         HttpGet httpGet = new HttpGet(urlPath);
12         HttpResponse response = client.execute(httpGet);
13         HttpEntity entity = response.getEntity();
14         long fileSize = entity.getContentLength();
15         fileESize = fileSize;   //將文件的大小賦值給全局量,以在panDiskConnect方法中判斷文件完整性
16         //關閉鏈接,誰知道能不能用,官方沒有找到關閉連接的方法,先來一套
17         client.getConnectionManager().shutdown();
18         if(file.getFreeSpace() > fileSize) {
19             System.out.println("磁盤容量知足");
20             return true;
21         }
22         return false;
23     }
判斷磁盤空間是否知足

若是文件不存在,將進行首次下載

 1 /**
 2      * 開始普通下載
 3      */
 4     private void startDownloadFile() {
 5         System.out.println("進入下載的url" + urlPath);
 6         try {
 7             HttpClient client = HttpClients.createDefault();
 8             
 9             HttpGet get = new HttpGet(urlPath);
10             HttpResponse response = client.execute(get);
11             HttpEntity entity = response.getEntity();
12             InputStream iStream = entity.getContent();
13             OutputStream oStream = new FileOutputStream(PanFlag + ":\\" + downloadPath + "\\"+ fileName_Disk);
14             int len = -1;
15             int p = 0;
16             byte[] temp = new byte[5120];
17             while ((len = iStream.read(temp)) !=-1) {
18                 oStream.write(temp,0,len);
19                 p = p +len;
20                 System.out.println("字節跳動==>"+p);
21             }
22             oStream.flush();
23             oStream.close();
24             iStream.close();
25             client.getConnectionManager().shutdown();
26         } catch (ClientProtocolException e) {
27             // TODO Auto-generated catch block
28             e.printStackTrace();
29         } catch (IOException e) {
30             // TODO Auto-generated catch block
31             e.printStackTrace();
32         }
33         
34     }
文件不存在首次下載

文件未下載完,進行斷點續傳

 1 /**
 2      * 斷點續傳方法
 3      */
 4     private void posDownload(File file) {
 5         //獲取現有文件的字節
 6         long fileLength = file.length();
 7         System.out.println("現有字節數:" + fileLength);
 8         try {
 9             HttpClient client = HttpClients.createDefault();
10             HttpGet get = new HttpGet(urlPath);
11             get.setHeader("Accept-Ranges","bytes");
12             get.setHeader("Range", " bytes="+fileLength+"-");
13             HttpResponse response = client.execute(get);
14             HttpEntity entity = response.getEntity();
15             InputStream iStream = entity.getContent();
16             //iStream.skip(fileLength);
17             OutputStream oStream = new FileOutputStream(PanFlag + ":\\" + downloadPath + "\\"+ fileName_Disk,true);
18             int len = -1;
19             int p = 0;
20             byte[] temp = new byte[5120];
21             while ((len = iStream.read(temp)) !=-1) {
22                 oStream.write(temp,0,len);
23                 p = p +len;
24                 System.out.println("字節跳動==>"+p);
25             }
26             oStream.flush();
27             oStream.close();
28             iStream.close();
29             client.getConnectionManager().shutdown();
30         } catch (ClientProtocolException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         } catch (IOException e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         }
37         
38     }
斷點續傳

判斷磁盤是否存在

 1 /**
 2      * 判斷用戶輸入的磁盤是否存在
 3      */
 4     private void panDiskConnect() {
 5         File fileisE = new File(PanFlag + ":\\" + downloadPath + "\\"+ fileName_Disk);
 6         File[] fs = File.listRoots();
 7         //將磁盤列表加入LISt集合
 8         for (File file : fs) {
 9             panS.add(file.toString().split(":")[0]);
10         }
11         //判斷磁盤是否存在
12         if(panS.contains(PanFlag)) {
13             try {
14                 //判斷磁盤容量是否充足
15                 if(panDiskSize()) {
16                     //判斷文件是否存在
17                     if(fileisE.isFile()) {
18                         System.out.println("文件長度"+fileESize);
19                         //判斷文件是否下載完整,由於懶因此沒有使用md5驗證了
20                         if(fileisE.length() == fileESize) {
21                             //若是下載完整就退出
22                             System.out.println("文件已經的完整的了");
23                             return;
24                         }else {
25                             //斷點續傳
26                             posDownload(fileisE);
27                         }
28                         
29                     }else {
30                         //文件不存在的普通直接下載
31                         startDownloadFile();
32                     }
33                 }
34             } catch (IOException e) {
35                 e.printStackTrace();
36             }
37         }else {
38             System.out.println("您輸入的磁盤盤符不存在");
39             return;
40         }
41     }
42     
判斷磁盤是否存在

這個類須要用的全局變量

1 private String urlPath = "";
2 private String PanFlag = "";
3 private String downloadPath = "";
4 private String fileName_Disk = "";
5 long fileESize = -1;
6 List<String> panS = new ArrayList<String>();
類須要的全局變量

run方法

1 @Override
2     public void run() {
3         panDiskConnect();
4     }
run方法

上面的代碼可能會有些亂,在家能夠去個人csdn下載:傳送門  今天上傳文件的時候不知道怎麼回事找不到修改積分的地方了,若是你們有積分但願支持下,若是沒有積分你們在下方評論處留自已的郵箱我發送給你們。

相關文章
相關標籤/搜索