java断点续传

本文来自:http://virgos.iteye.com/blog/254590

SiteFileFetch.java负责整个文件的抓取,控制内部线程(FileSplitterFetch类)。
FileSplitterFetch.java负责部分文件的抓取。
FileAccess.java负责文件的存储。
SiteInfoBean.java要抓取的文件的信息,如文件保存的目录,名字,抓取文件的URL等。
Utility.java工具类,放一些简单的方法。
TestMethod.java测试类

Java代码 复制代码  收藏代码
  1. /*  
  2. **SiteFileFetch.java  
  3. */  
  4. package NetFox;   
  5. import java.io.*;   
  6. import java.net.*;   
  7. public class SiteFileFetch extends Thread {   
  8. SiteInfoBean siteInfoBean = null//文件信息Bean   
  9. long[] nStartPos; //开始位置   
  10. long[] nEndPos; //结束位置   
  11. FileSplitterFetch[] fileSplitterFetch; //子线程对象   
  12. long nFileLength; //文件长度   
  13. boolean bFirst = true//是否第一次取文件   
  14. boolean bStop = false//停止标志   
  15. File tmpFile; //文件下载的临时信息   
  16. DataOutputStream output; //输出到文件的输出流   
  17. public SiteFileFetch(SiteInfoBean bean) throws IOException   
  18. {   
  19. siteInfoBean = bean;   
  20. //tmpFile = File.createTempFile ("zhong","1111",new File(bean.getSFilePath()));   
  21. tmpFile = new File(bean.getSFilePath()+File.separator + bean.getSFileName()+".info");   
  22. if(tmpFile.exists ())   
  23. {   
  24. bFirst = false;   
  25. read_nPos();   
  26. }   
  27. else  
  28. {   
  29. nStartPos = new long[bean.getNSplitter()];   
  30. nEndPos = new long[bean.getNSplitter()];   
  31. }   
  32. }   
  33. public void run()   
  34. {   
  35. //获得文件长度   
  36. //分割文件   
  37. //实例FileSplitterFetch   
  38. //启动FileSplitterFetch线程   
  39. //等待子线程返回   
  40. try{   
  41. if(bFirst)   
  42. {   
  43. nFileLength = getFileSize();   
  44. if(nFileLength == -1)   
  45. {   
  46. System.err.println("File Length is not known!");   
  47. }   
  48. else if(nFileLength == -2)   
  49. {   
  50. System.err.println("File is not access!");   
  51. }   
  52. else  
  53. {   
  54. for(int i=0;i<nStartPos.length;i++)   
  55. {   
  56. nStartPos[i] = (long)(i*(nFileLength/nStartPos.length));   
  57. }   
  58. for(int i=0;i<nEndPos.length-1;i++)   
  59. {   
  60. nEndPos[i] = nStartPos[i+1];   
  61. }   
  62. nEndPos[nEndPos.length-1] = nFileLength;   
  63. }   
  64. }   
  65. //启动子线程   
  66. fileSplitterFetch = new FileSplitterFetch[nStartPos.length];   
  67. for(int i=0;i<nStartPos.length;i++)   
  68. {   
  69. fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),   
  70. siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),   
  71. nStartPos[i],nEndPos[i],i);   
  72. Utility.log("Thread " + i + " , nStartPos = " + nStartPos[i] + ", nEndPos = " + nEndPos[i]);   
  73. fileSplitterFetch[i].start();   
  74. }   
  75. // fileSplitterFetch[nPos.length-1] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),   
  76. siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),nPos[nPos.length-1],nFileLength,nPos.length-1);   
  77. // Utility.log("Thread " + (nPos.length-1) + " , nStartPos = " + nPos[nPos.length-1] + ",   
  78. nEndPos = " + nFileLength);   
  79. // fileSplitterFetch[nPos.length-1].start();   
  80. //等待子线程结束   
  81. //int count = 0;   
  82. //是否结束while循环   
  83. boolean breakWhile = false;   
  84. while(!bStop)   
  85. {   
  86. write_nPos();   
  87. Utility.sleep(500);   
  88. breakWhile = true;   
  89. for(int i=0;i<nStartPos.length;i++)   
  90. {   
  91. if(!fileSplitterFetch[i].bDownOver)   
  92. {   
  93. breakWhile = false;   
  94. break;   
  95. }   
  96. }   
  97. if(breakWhile)   
  98. break;   
  99. //count++;   
  100. //if(count>4)   
  101. // siteStop();   
  102. }   
  103. System.err.println("文件下载结束!");   
  104. }   
  105. catch(Exception e){e.printStackTrace ();}   
  106. }   
  107. //获得文件长度   
  108. public long getFileSize()   
  109. {   
  110. int nFileLength = -1;   
  111. try{   
  112. URL url = new URL(siteInfoBean.getSSiteURL());   
  113. HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();   
  114. httpConnection.setRequestProperty("User-Agent","NetFox");   
  115. int responseCode=httpConnection.getResponseCode();   
  116. if(responseCode>=400)   
  117. {   
  118. processErrorCode(responseCode);   
  119. return -2//-2 represent access is error   
  120. }   
  121. String sHeader;   
  122. for(int i=1;;i++)   
  123. {   
  124. //DataInputStream in = new DataInputStream(httpConnection.getInputStream ());   
  125. //Utility.log(in.readLine());   
  126. sHeader=httpConnection.getHeaderFieldKey(i);   
  127. if(sHeader!=null)   
  128. {   
  129. if(sHeader.equals("Content-Length"))   
  130. {   
  131. nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));   
  132. break;   
  133. }   
  134. }   
  135. else  
  136. break;   
  137. }   
  138. }   
  139. catch(IOException e){e.printStackTrace ();}   
  140. catch(Exception e){e.printStackTrace ();}   
  141. Utility.log(nFileLength);   
  142. return nFileLength;   
  143. }   
  144. //保存下载信息(文件指针位置)   
  145. private void write_nPos()   
  146. {   
  147. try{   
  148. output = new DataOutputStream(new FileOutputStream(tmpFile));   
  149. output.writeInt(nStartPos.length);   
  150. for(int i=0;i<nStartPos.length;i++)   
  151. {   
  152. // output.writeLong(nPos[i]);   
  153. output.writeLong(fileSplitterFetch[i].nStartPos);   
  154. output.writeLong(fileSplitterFetch[i].nEndPos);   
  155. }   
  156. output.close();   
  157. }   
  158. catch(IOException e){e.printStackTrace ();}   
  159. catch(Exception e){e.printStackTrace ();}   
  160. }   
  161. //读取保存的下载信息(文件指针位置)   
  162. private void read_nPos()   
  163. {   
  164. try{   
  165. DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));   
  166. int nCount = input.readInt();   
  167. nStartPos = new long[nCount];   
  168. nEndPos = new long[nCount];   
  169. for(int i=0;i<nStartPos.length;i++)   
  170. {   
  171. nStartPos[i] = input.readLong();   
  172. nEndPos[i] = input.readLong();   
  173. }   
  174. input.close();   
  175. }   
  176. catch(IOException e){e.printStackTrace ();}   
  177. catch(Exception e){e.printStackTrace ();}   
  178. }   
  179. private void processErrorCode(int nErrorCode)   
  180. {   
  181. System.err.println("Error Code : " + nErrorCode);   
  182. }   
  183. //停止文件下载   
  184. public void siteStop()   
  185. {   
  186. bStop = true;   
  187. for(int i=0;i<nStartPos.length;i++)   
  188. fileSplitterFetch[i].splitterStop();   
  189. }   
  190. }  
/*
**SiteFileFetch.java
*/
package NetFox;
import java.io.*;
import java.net.*;
public class SiteFileFetch extends Thread {
SiteInfoBean siteInfoBean = null; //文件信息Bean
long[] nStartPos; //开始位置
long[] nEndPos; //结束位置
FileSplitterFetch[] fileSplitterFetch; //子线程对象
long nFileLength; //文件长度
boolean bFirst = true; //是否第一次取文件
boolean bStop = false; //停止标志
File tmpFile; //文件下载的临时信息
DataOutputStream output; //输出到文件的输出流
public SiteFileFetch(SiteInfoBean bean) throws IOException
{
siteInfoBean = bean;
//tmpFile = File.createTempFile ("zhong","1111",new File(bean.getSFilePath()));
tmpFile = new File(bean.getSFilePath()+File.separator + bean.getSFileName()+".info");
if(tmpFile.exists ())
{
bFirst = false;
read_nPos();
}
else
{
nStartPos = new long[bean.getNSplitter()];
nEndPos = new long[bean.getNSplitter()];
}
}
public void run()
{
//获得文件长度
//分割文件
//实例FileSplitterFetch
//启动FileSplitterFetch线程
//等待子线程返回
try{
if(bFirst)
{
nFileLength = getFileSize();
if(nFileLength == -1)
{
System.err.println("File Length is not known!");
}
else if(nFileLength == -2)
{
System.err.println("File is not access!");
}
else
{
for(int i=0;i<nStartPos.length;i++)
{
nStartPos[i] = (long)(i*(nFileLength/nStartPos.length));
}
for(int i=0;i<nEndPos.length-1;i++)
{
nEndPos[i] = nStartPos[i+1];
}
nEndPos[nEndPos.length-1] = nFileLength;
}
}
//启动子线程
fileSplitterFetch = new FileSplitterFetch[nStartPos.length];
for(int i=0;i<nStartPos.length;i++)
{
fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),
siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),
nStartPos[i],nEndPos[i],i);
Utility.log("Thread " + i + " , nStartPos = " + nStartPos[i] + ", nEndPos = " + nEndPos[i]);
fileSplitterFetch[i].start();
}
// fileSplitterFetch[nPos.length-1] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),
siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),nPos[nPos.length-1],nFileLength,nPos.length-1);
// Utility.log("Thread " + (nPos.length-1) + " , nStartPos = " + nPos[nPos.length-1] + ",
nEndPos = " + nFileLength);
// fileSplitterFetch[nPos.length-1].start();
//等待子线程结束
//int count = 0;
//是否结束while循环
boolean breakWhile = false;
while(!bStop)
{
write_nPos();
Utility.sleep(500);
breakWhile = true;
for(int i=0;i<nStartPos.length;i++)
{
if(!fileSplitterFetch[i].bDownOver)
{
breakWhile = false;
break;
}
}
if(breakWhile)
break;
//count++;
//if(count>4)
// siteStop();
}
System.err.println("文件下载结束!");
}
catch(Exception e){e.printStackTrace ();}
}
//获得文件长度
public long getFileSize()
{
int nFileLength = -1;
try{
URL url = new URL(siteInfoBean.getSSiteURL());
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();
httpConnection.setRequestProperty("User-Agent","NetFox");
int responseCode=httpConnection.getResponseCode();
if(responseCode>=400)
{
processErrorCode(responseCode);
return -2; //-2 represent access is error
}
String sHeader;
for(int i=1;;i++)
{
//DataInputStream in = new DataInputStream(httpConnection.getInputStream ());
//Utility.log(in.readLine());
sHeader=httpConnection.getHeaderFieldKey(i);
if(sHeader!=null)
{
if(sHeader.equals("Content-Length"))
{
nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
break;
}
}
else
break;
}
}
catch(IOException e){e.printStackTrace ();}
catch(Exception e){e.printStackTrace ();}
Utility.log(nFileLength);
return nFileLength;
}
//保存下载信息(文件指针位置)
private void write_nPos()
{
try{
output = new DataOutputStream(new FileOutputStream(tmpFile));
output.writeInt(nStartPos.length);
for(int i=0;i<nStartPos.length;i++)
{
// output.writeLong(nPos[i]);
output.writeLong(fileSplitterFetch[i].nStartPos);
output.writeLong(fileSplitterFetch[i].nEndPos);
}
output.close();
}
catch(IOException e){e.printStackTrace ();}
catch(Exception e){e.printStackTrace ();}
}
//读取保存的下载信息(文件指针位置)
private void read_nPos()
{
try{
DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));
int nCount = input.readInt();
nStartPos = new long[nCount];
nEndPos = new long[nCount];
for(int i=0;i<nStartPos.length;i++)
{
nStartPos[i] = input.readLong();
nEndPos[i] = input.readLong();
}
input.close();
}
catch(IOException e){e.printStackTrace ();}
catch(Exception e){e.printStackTrace ();}
}
private void processErrorCode(int nErrorCode)
{
System.err.println("Error Code : " + nErrorCode);
}
//停止文件下载
public void siteStop()
{
bStop = true;
for(int i=0;i<nStartPos.length;i++)
fileSplitterFetch[i].splitterStop();
}
}



Java代码 复制代码  收藏代码
  1. /*  
  2. **FileSplitterFetch.java  
  3. */  
  4. package NetFox;   
  5. import java.io.*;   
  6. import java.net.*;   
  7. public class FileSplitterFetch extends Thread {   
  8. String sURL; //File URL   
  9. long nStartPos; //File Snippet Start Position   
  10. long nEndPos; //File Snippet End Position   
  11. int nThreadID; //Thread's ID   
  12. boolean bDownOver = false//Downing is over   
  13. boolean bStop = false//Stop identical   
  14. FileAccessI fileAccessI = null//File Access interface   
  15. public FileSplitterFetch(String sURL,String sName,long nStart,long nEnd,int id) throws IOException   
  16. {   
  17. this.sURL = sURL;   
  18. this.nStartPos = nStart;   
  19. this.nEndPos = nEnd;   
  20. nThreadID = id;   
  21. fileAccessI = new FileAccessI(sName,nStartPos);   
  22. }   
  23. public void run()   
  24. {   
  25. while(nStartPos < nEndPos && !bStop)   
  26. {   
  27. try{   
  28. URL url = new URL(sURL);   
  29. HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();   
  30. httpConnection.setRequestProperty("User-Agent","NetFox");   
  31. String sProperty = "bytes="+nStartPos+"-";   
  32. httpConnection.setRequestProperty("RANGE",sProperty);   
  33. Utility.log(sProperty);   
  34. InputStream input = httpConnection.getInputStream();   
  35. //logResponseHead(httpConnection);   
  36. byte[] b = new byte[1024];   
  37. int nRead;   
  38. while((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos && !bStop)   
  39. {   
  40. nStartPos += fileAccessI.write(b,0,nRead);   
  41. //if(nThreadID == 1)   
  42. // Utility.log("nStartPos = " + nStartPos + ", nEndPos = " + nEndPos);   
  43. }   
  44. Utility.log("Thread " + nThreadID + " is over!");   
  45. bDownOver = true;   
  46. //nPos = fileAccessI.write (b,0,nRead);   
  47. }   
  48. catch(Exception e){e.printStackTrace ();}   
  49. }   
  50. }   
  51. //打印回应的头信息   
  52. public void logResponseHead(HttpURLConnection con)   
  53. {   
  54. for(int i=1;;i++)   
  55. {   
  56. String header=con.getHeaderFieldKey(i);   
  57. if(header!=null)   
  58. //responseHeaders.put(header,httpConnection.getHeaderField(header));   
  59. Utility.log(header+" : "+con.getHeaderField(header));   
  60. else  
  61. break;   
  62. }   
  63. }   
  64. public void splitterStop()   
  65. {   
  66. bStop = true;   
  67. }   
  68. }  
/*
**FileSplitterFetch.java
*/
package NetFox;
import java.io.*;
import java.net.*;
public class FileSplitterFetch extends Thread {
String sURL; //File URL
long nStartPos; //File Snippet Start Position
long nEndPos; //File Snippet End Position
int nThreadID; //Thread's ID
boolean bDownOver = false; //Downing is over
boolean bStop = false; //Stop identical
FileAccessI fileAccessI = null; //File Access interface
public FileSplitterFetch(String sURL,String sName,long nStart,long nEnd,int id) throws IOException
{
this.sURL = sURL;
this.nStartPos = nStart;
this.nEndPos = nEnd;
nThreadID = id;
fileAccessI = new FileAccessI(sName,nStartPos);
}
public void run()
{
while(nStartPos < nEndPos && !bStop)
{
try{
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();
httpConnection.setRequestProperty("User-Agent","NetFox");
String sProperty = "bytes="+nStartPos+"-";
httpConnection.setRequestProperty("RANGE",sProperty);
Utility.log(sProperty);
InputStream input = httpConnection.getInputStream();
//logResponseHead(httpConnection);
byte[] b = new byte[1024];
int nRead;
while((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos && !bStop)
{
nStartPos += fileAccessI.write(b,0,nRead);
//if(nThreadID == 1)
// Utility.log("nStartPos = " + nStartPos + ", nEndPos = " + nEndPos);
}
Utility.log("Thread " + nThreadID + " is over!");
bDownOver = true;
//nPos = fileAccessI.write (b,0,nRead);
}
catch(Exception e){e.printStackTrace ();}
}
}
//打印回应的头信息
public void logResponseHead(HttpURLConnection con)
{
for(int i=1;;i++)
{
String header=con.getHeaderFieldKey(i);
if(header!=null)
//responseHeaders.put(header,httpConnection.getHeaderField(header));
Utility.log(header+" : "+con.getHeaderField(header));
else
break;
}
}
public void splitterStop()
{
bStop = true;
}
}



Java代码 复制代码  收藏代码
  1. /*  
  2. **FileAccess.java  
  3. */  
  4. package NetFox;   
  5. import java.io.*;   
  6. public class FileAccessI implements Serializable{   
  7. RandomAccessFile oSavedFile;   
  8. long nPos;   
  9. public FileAccessI() throws IOException   
  10. {   
  11. this("",0);   
  12. }   
  13. public FileAccessI(String sName,long nPos) throws IOException   
  14. {   
  15. oSavedFile = new RandomAccessFile(sName,"rw");   
  16. this.nPos = nPos;   
  17. oSavedFile.seek(nPos);   
  18. }   
  19. public synchronized int write(byte[] b,int nStart,int nLen)   
  20. {   
  21. int n = -1;   
  22. try{   
  23. oSavedFile.write(b,nStart,nLen);   
  24. n = nLen;   
  25. }   
  26. catch(IOException e)   
  27. {   
  28. e.printStackTrace ();   
  29. }   
  30. return n;   
  31. }   
  32. }  
/*
**FileAccess.java
*/
package NetFox;
import java.io.*;
public class FileAccessI implements Serializable{
RandomAccessFile oSavedFile;
long nPos;
public FileAccessI() throws IOException
{
this("",0);
}
public FileAccessI(String sName,long nPos) throws IOException
{
oSavedFile = new RandomAccessFile(sName,"rw");
this.nPos = nPos;
oSavedFile.seek(nPos);
}
public synchronized int write(byte[] b,int nStart,int nLen)
{
int n = -1;
try{
oSavedFile.write(b,nStart,nLen);
n = nLen;
}
catch(IOException e)
{
e.printStackTrace ();
}
return n;
}
}



Java代码 复制代码  收藏代码
  1. /*  
  2. **SiteInfoBean.java  
  3. */  
  4. package NetFox;   
  5. public class SiteInfoBean {   
  6. private String sSiteURL; //Site's URL   
  7. private String sFilePath; //Saved File's Path   
  8. private String sFileName; //Saved File's Name   
  9. private int nSplitter; //Count of Splited Downloading File   
  10. public SiteInfoBean()   
  11. {   
  12. //default value of nSplitter is 5   
  13. this("","","",5);   
  14. }   
  15. public SiteInfoBean(String sURL,String sPath,String sName,int nSpiltter)   
  16. {   
  17. sSiteURL= sURL;   
  18. sFilePath = sPath;   
  19. sFileName = sName;   
  20. this.nSplitter = nSpiltter;   
  21. }   
  22. public String getSSiteURL()   
  23. {   
  24. return sSiteURL;   
  25. }   
  26. public void setSSiteURL(String value)   
  27. {   
  28. sSiteURL = value;   
  29. }   
  30. public String getSFilePath()   
  31. {   
  32. return sFilePath;   
  33. }   
  34. public void setSFilePath(String value)   
  35. {   
  36. sFilePath = value;   
  37. }   
  38. public String getSFileName()   
  39. {   
  40. return sFileName;   
  41. }   
  42. public void setSFileName(String value)   
  43. {   
  44. sFileName = value;   
  45. }   
  46. public int getNSplitter()   
  47. {   
  48. return nSplitter;   
  49. }   
  50. public void setNSplitter(int nCount)   
  51. {   
  52. nSplitter = nCount;   
  53. }   
  54. }  
/*
**SiteInfoBean.java
*/
package NetFox;
public class SiteInfoBean {
private String sSiteURL; //Site's URL
private String sFilePath; //Saved File's Path
private String sFileName; //Saved File's Name
private int nSplitter; //Count of Splited Downloading File
public SiteInfoBean()
{
//default value of nSplitter is 5
this("","","",5);
}
public SiteInfoBean(String sURL,String sPath,String sName,int nSpiltter)
{
sSiteURL= sURL;
sFilePath = sPath;
sFileName = sName;
this.nSplitter = nSpiltter;
}
public String getSSiteURL()
{
return sSiteURL;
}
public void setSSiteURL(String value)
{
sSiteURL = value;
}
public String getSFilePath()
{
return sFilePath;
}
public void setSFilePath(String value)
{
sFilePath = value;
}
public String getSFileName()
{
return sFileName;
}
public void setSFileName(String value)
{
sFileName = value;
}
public int getNSplitter()
{
return nSplitter;
}
public void setNSplitter(int nCount)
{
nSplitter = nCount;
}
}



Java代码 复制代码  收藏代码
  1. /*  
  2. **Utility.java  
  3. */  
  4. package NetFox;   
  5. public class Utility {   
  6. public Utility()   
  7. {   
  8. }   
  9. public static void sleep(int nSecond)   
  10. {   
  11. try{   
  12. Thread.sleep(nSecond);   
  13. }   
  14. catch(Exception e)   
  15. {   
  16. e.printStackTrace ();   
  17. }   
  18. }   
  19. public static void log(String sMsg)   
  20. {   
  21. System.err.println(sMsg);   
  22. }   
  23. public static void log(int sMsg)   
  24. {   
  25. System.err.println(sMsg);   
  26. }   
  27. }  
/*
**Utility.java
*/
package NetFox;
public class Utility {
public Utility()
{
}
public static void sleep(int nSecond)
{
try{
Thread.sleep(nSecond);
}
catch(Exception e)
{
e.printStackTrace ();
}
}
public static void log(String sMsg)
{
System.err.println(sMsg);
}
public static void log(int sMsg)
{
System.err.println(sMsg);
}
}



Java代码 复制代码  收藏代码
  1. /*  
  2. **TestMethod.java  
  3. */  
  4. package NetFox;   
  5. public class TestMethod {   
  6. public TestMethod()   
  7. ///xx/weblogic60b2_win.exe   
  8. try{   
  9. SiteInfoBean bean = new SiteInfoBean("http://localhost/xx/weblogic60b2_win.exe","L:\\temp","weblogic60b2_win.exe",5);   
  10. //SiteInfoBean bean = new SiteInfoBean("http://localhost:8080/down.zip","L:\\temp","weblogic60b2_win.exe",5);   
  11. SiteFileFetch fileFetch = new SiteFileFetch(bean);   
  12. fileFetch.start();   
  13. }   
  14. catch(Exception e){e.printStackTrace ();}   
  15. }   
  16. public static void main(String[] args)   
  17. {   
  18. new TestMethod();   
  19. }   
  20. }  

你可能感兴趣的:(java,thread,.net,bean,Access)