⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 downloadthread.java

📁 java 多线程文件下载器源代码......
💻 JAVA
字号:
package com.sam.net.download;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JTextArea;


public class DownloadThread extends Thread {
    URL url;
    long startPos;
    long endPos;
    boolean done = false;
    boolean isstop = true;
    RandomAccessFile file = null;
    InputStream stream = null;
    String filename;
    String savaAs;
    Search search;
    long writePos;

    public DownloadThread(URL url, String saveAs, long startPos,long endPos,Search search) throws IOException {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.savaAs = saveAs;
        this.search = search;
        search.downloaded = 1;
    }
    
    public DownloadThread (){
    	
    }

    public void run() {
    	while(isstop){
        try {
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
			huc.setAllowUserInteraction(true);
			huc.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
			file = new RandomAccessFile(savaAs, "rw");
            file.seek(startPos);
            stream = huc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(stream);
            byte[] buf = new byte[1024];
            int tmp, bytesRead;
            tmp = (int)( endPos -  startPos);
            tmp = (tmp > 1024) ? 1024:tmp;
            while ((bytesRead = bis.read(buf, 0, tmp))!= -1 && startPos < endPos) {
                file.write(buf, 0, bytesRead);
                startPos += bytesRead;
                tmp = (int) (endPos -  startPos);
                tmp = (tmp > 1024) ? 1024:tmp;
                search.downloaded += bytesRead;
                search.stateChanged();
            }
            file.close();
            bis.close();
            done = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    }
    
    public void setstop(boolean isstiop)
    {
    	this.isstop = isstop;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -