📄 downfilesplitter.java
字号:
import java.io.*;
import java.net.*;
import javax.swing.JTextArea;
/*
* DownFileSplitter.java
*
* Created on 2006年12月11日, 下午1:25
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
//下载指定的段
/**********************************************************************************************/
/*类设计:
*类名:DownFileSplitter;
*功能:实现对指定段文件数据的下载;
*方法:
* 构造方法DownFileSplitter(String localFilePath,
* String stringURL,int startPos,int endPos);
* 线程方法run();
* 下载数据段方法getPartFile();
*
*
*
*
*/
/************************************************************************************************/
public class DownFileSplitter extends Thread{
String localFilePath;
String stringURL;
boolean bDownOver=false;
JTextArea messageJTextArea;
int startPos;
int endPos;
int mark;
/** Creates a new instance of DownFileSplitter */
//构造方法,初始化属性
public DownFileSplitter(String localFilePath,
String stringURL,int startPos,int endPos,JTextArea messageJTextArea,int mark) {
this.localFilePath=localFilePath;
this.stringURL=stringURL;
this.messageJTextArea=messageJTextArea;
this.startPos=startPos;
this.endPos=endPos;
this.mark=mark;
}
public void getPartFile(){
URL url;
HttpURLConnection hURL;
RandomAccessFile file;
int partLength=(int)(endPos-startPos);
//System.out.println("文件段长度:"+partLength);
int length=0;
try {
url=new URL(stringURL);
hURL=(HttpURLConnection) url.openConnection();
String sProperty="bytes="+startPos+"-";
//System.out.println("文件开始下载位置:"+sProperty);
hURL.setRequestProperty("RANGE",sProperty);
BufferedInputStream bIn=new BufferedInputStream(hURL.getInputStream());
byte[] buf=new byte[1024];
int len;
file=new RandomAccessFile(localFilePath,"rw");
file.seek(startPos);
while((len=bIn.read(buf))!=-1){
if(len>partLength-length){
len=partLength-length;
}
file.write(buf,0,len);
//System.out.println(len);
length+=len;
if(length>=partLength){
messageJTextArea.append("\n子线程"+mark+"下载完毕!");
hURL.disconnect();
file.close();
break;
}
bDownOver=true;
}
//System.out.println("\n子线程"+mark+"下载文件长度:"+length);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void run(){
//System.out.println("\n子线程"+mark+"下载中.....");
messageJTextArea.append("\n子线程"+mark+"下载中......");
getPartFile();
}
//供此类测试用
// public static void main(String[] args) {
// String urlString=new String("http://www.zhouyunhai.com/book/whomovedmycheese.exe");
// String filePart=new String("H:\\2.exe");
// DownFileSplitter downFile0=new DownFileSplitter(filePart,urlString,0,1024);
// DownFileSplitter downFile1=new DownFileSplitter(filePart,urlString,1024,2048);
// DownFileSplitter downFile2=new DownFileSplitter(filePart,urlString,2048,1000000);
// downFile0.start();
// downFile1.start();
// downFile2.start();
// }
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -