當前位置:編程學習大全網 - 源碼下載 - Java Socket如何實現文件的斷點續傳,有代碼更好

Java Socket如何實現文件的斷點續傳,有代碼更好

1package com.tangshun.www.socket;

2

3import java.io.File;

4import java.io.IOException;

5import java.io.InputStream;

6import java.io.RandomAccessFile;

7import java.net.HttpURLConnection;

8import java.net.MalformedURLException;

9import java.net.URL;

10

11//斷點續傳

12public class DownLoad {

13

14 public static void down(String URL, long nPos, String savePathAndFile) {

15 try {

16 URL url = new URL(URL);

17 HttpURLConnection /media/0/16/8678/8678.flv";

58 String savePath = "F:\\";

59 String fileName = url.substring(url.lastIndexOf("/"));

60 String fileNam=fileName;

61 HttpURLConnection conn = null;

62 try {

63 conn = (HttpURLConnection) (new URL(url)).openConnection();

64 } catch (Exception e) {

65 e.printStackTrace();

66 }

67 File file = new File(savePath + fileName);

68 // 獲得遠程文件大小

69 long remoteFileSize = getRemoteFileSize(url);

70 System.out.println("遠程文件大小="+remoteFileSize);

71 int i = 0;

72 if (file.exists()) {

73 // 先看看是否是完整的,完整,換名字,跳出循環,不完整,繼續下載

74 long localFileSize = file.length();

75 System.out.println("已有文件大小為:"+localFileSize);

76

77 if (localFileSize < remoteFileSize) {

78 System.out.println("文件續傳");

79 down(url, localFileSize, savePath + fileName);

80 }else{

81 System.out.println("文件存在,重新下載");

82 do{

83 i++;

84 fileName = fileNam.substring(0, fileNam.indexOf(".")) + "(" + i

85 + ")" + fileNam.substring(fileNam.indexOf("."));

86

87 file = new File(savePath + fileName);

88 }while(file.exists());

89 try {

90 file.createNewFile();

91 } catch (IOException e) {

92 e.printStackTrace();

93 }

94 down(url, 0, savePath + fileName);

95 }

96 // 下面表示文件存在,改名字

97

98 } else {

99 try {

100 file.createNewFile();

101 System.out.println("下載中");

102 down(url, 0, savePath + fileName);

103 } catch (IOException e) {

104 e.printStackTrace();

105 }

106 }

107 }}

108

  • 上一篇:復制JD.COM源代碼
  • 下一篇:誰有Kumi Kouda的CUTIE HONEY的中文翻譯?
  • copyright 2024編程學習大全網