/**
*
* @author yw04009 Bill, Wu
*
*/
public class Testdownload {
public void Testonethread (string filePath, String url) throws IOException {
File File = new file (FilePath + getfileextname (URL));
FileWriter fwriter = new FileWriter (file);
URL ul = new URL (URL);
URLConnection conn = Ul.openconnection ();
Conn.setconnecttimeout (2000);
InputStream in = Conn.getinputstream ();
int temp = 0;
while (temp = In.read ())!=-1) {
Fwriter.write (temp);
}
Fwriter.close ();
In.close ();
}
public string Getfileextname (string path) {
Return path.substring (Path.lastindexof ("."));
}
public void Testmorethread (string filePath, string url, int tnum) throws IOException {
Final file File = new file (FilePath + getfileextname (URL));
Randomaccessfile accessfile = new Randomaccessfile (file, "RWD");
Final URL ul = new URL (URL);
HttpURLConnection conn = (httpurlconnection) ul.openconnection ();
Conn.setconnecttimeout (2000);
Conn.setrequestmethod ("get");
int len = Conn.getcontentlength ();
Accessfile.setlength (len);
Accessfile.close ();
Final int block = (len + tnum-1)/tnum; The size for every thread download
for (int i = 0; i < Tnum; i++) {
final int a = i;
New Thread (New Runnable () {
int start = block * A; Start Place
int end = Block * (A + 1)-1; End Place
public void Run () {
TODO auto-generated Method Stub
HttpURLConnection conn2 = null;
Randomaccessfile accessFile2 = null;
InputStream in = null;
try {
CONN2 = (httpurlconnection) ul.openconnection ();
Conn2.setconnecttimeout (2000);
Conn2.setrequestmethod ("get");
Conn2.setrequestproperty ("Range", "bytes=" + Start
+ "-" + End + "");
in = Conn2.getinputstream ();
byte[] data = new byte[1024];
int len = 0;
AccessFile2 = new Randomaccessfile (file, "RWD");
Accessfile2.seek (start);
while (len = in.read (data))!=-1) {
Accessfile2.write (data, 0, Len);
}
System.out.println ("This Thread Download is compled ...");
catch (IOException e) {
}
}
). Start ();
}
}
public static void Main (string[] args) throws IOException {
Testdownload test = new Testdownload ();
String Path = "Http://bill.com/test.txt";
Test.testonethread ("C:\\code\\test1", Path);
Test.testmorethread ("C:\\code\\test2", Path, 3); }
}