阅读背景:

多线程并发下载同一文件DEMO

来源:互联网 

DownloadFile.java

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class DownloadFile {
	private File file;
	private String url;
	private int startPos;
	private int endPos;
	private int totalSize;
	private String fileName;
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public int getStartPos() {
		return startPos;
	}
	public void setStartPos(int startPos) {
		this.startPos = startPos;
	}
	public int getEndPos() {
		return endPos;
	}
	public void setEndPos(int endPos) {
		this.endPos = endPos;
	}
	public int getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public int getURLTotalSize() throws Exception{
		int total = 0;
		if(this.url != null && !"".equals(this.url)){
			URL url = new URL(this.url);
			HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
			return httpConn.getContentLength();
		}
		return total;
	}
	public InputStream getInputStream(){
		InputStream is = null;
		try{
			if(this.url != null && !"".equals(this.url)){
				URL url = new URL(this.url);
				HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
				httpConn.setRequestProperty("Connection", "Keep-Alive");  //保持一直连接
				httpConn.setConnectTimeout(60 * 1000 * 5);                //连接超时5分钟
				httpConn.setRequestMethod("POST");                         //以GET方式连接
				httpConn.setAllowUserInteraction(true);
				if(this.startPos != 0 || this.endPos != 0){
					httpConn.setRequestProperty("Range", "bytes=" + getStartPos() + "-" + getEndPos());
				}
				return new BufferedInputStream(httpConn.getInputStream(),1024*8);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return is;
	}
	
	public static void main(String[] args) throws Exception {
		DownloadFile downloadFile = new DownloadFile();
		downloadFile.setUrl("https://localhost:8080/navigater/admin/123.txt");
		downloadFile.setStartPos(5);
		downloadFile.setEndPos(880);
		InputStream is = downloadFile.getInputStream();
		System.out.println("is------>" +is.available());
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String str = null;
		while(null != (str = br.readLine())){
			System.out.println(str);
		}
	}
}
import java.io.BufferedI



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: