当前位置:首页 » JAVA技术教程

java多线程下载

2008-07-04 14:51 本站整理 浏览(8)
import javax.swing.JOptionPane;

public class getFile {

	/**

	 * @param args

	 */

	public static void main(String[] args) {

		

		// パラメーターを設定する

		downLoadParameter parameter = downLoadParameter.getInstance();

		// 画像のurl

		parameter.setDownLoadImageUrl("http://127.0.0.1:8080/tomcat-power.gif");

		// 画像の保存パース

		parameter.setSavePath("D://imageTesttt");

		// 画像の保存名

		parameter.setSaveName("image2.jpg");

		// スレッドの数を設定する

		parameter.setThreadCount(2);

		

        try {

        	

			MainThread main = new MainThread(parameter);

			main.start();

			

			MergeFile merge = new MergeFile(parameter);

			merge.start();

			

		} catch (Exception e) {

			

			e.printStackTrace();

			

		}

	}

	

	

}

import java.net.HttpURLConnection;

public class downLoadParameter {

	// 画像のurl

	private String downLoadImageUrl;

	// 画像の保存パース

	private String savePath;

    // 画像の保存名

	private String saveName;

	// 最終結果

	private String compleState;

    // フォーマット

	private String encoding;

    // スレッドの数

	private int threadCount;

    // 完成したスレッドの数

	public int compleThreadCount;

	// エラー

	public static final String ERROR = "-1";

	// 成功

	public static final String SUCCESS = "1";

	// 指定したURLへの接続

	private HttpURLConnection connection;

	

	public String getDownLoadImageUrl() {

		return downLoadImageUrl;

	}

	public void setDownLoadImageUrl(String downLoadImageUrl) {

		this.downLoadImageUrl = downLoadImageUrl;

	}

	public String getSaveName() {

		return saveName;

	}

	public void setSaveName(String saveName) {

		this.saveName = saveName;

	}

	public String getSavePath() {

		return savePath;

	}

	public void setSavePath(String savePath) {

		this.savePath = savePath;

	}

	public int getThreadCount() {

		return threadCount;

	}

	public void setThreadCount(int threadCount) {

		this.threadCount = threadCount;

		compleThreadCount = threadCount;

	}

	public String getCompleState() {

		return compleState;

	}

	public void setCompleState(String compleState) {

		this.compleState = compleState;

	}

	public String getEncoding() {

		return encoding;

	}

	public void setEncoding(String encoding) {

		this.encoding = encoding;

	}

	public HttpURLConnection getConnection() {

		return connection;

	}

	public void setConnection(HttpURLConnection connection) {

		this.connection = connection;

	}

	

	public boolean downLoadComple() {

		

		return compleThreadCount == 0;

		

	}

	

	public static downLoadParameter getInstance() {

		

		return new downLoadParameter();

		

	}

}

import java.io.File;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

/*守护进程*/

public class MainThread extends Thread{

	

	// 配置パラメーター

	downLoadParameter args;

	public MainThread(downLoadParameter args) {

		

		this.args = args;

		

	}

	

	public void run() {

		

		try {

			

			// 接続を作成する

			URL url = new URL(args.getDownLoadImageUrl());

			

			if (url == null) {

				

				return;

				

			}

			

	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

	        

	        int contentLength = connection.getContentLength();

	        

	        if (contentLength <= 0) {

	        	

	        	args.setCompleState("aa");

	        	return;

	        	

	        }

	

	        new File(args.getSavePath()).mkdir();

	        

	        

	        int partLength = contentLength / args.getThreadCount() + 1;

	        for (int i=0; i < args.getThreadCount(); i++) {

	        	

	        	// データの開始位置

	            int length = partLength;

	            if (i == args.getThreadCount() - 1) {

	            	

	                length = contentLength - i * partLength;

	                

	            }

	            

	            // ワークスレッドを起動する

	            WorkThread dt = new WorkThread(args, length, i * partLength);

	            dt.setName("part" + i);

	            dt.start();

	        }

	        

	        

			

		} catch (Exception e) {

			

			args.setCompleState(downLoadParameter.ERROR);

		} 

		

	}

}

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

public class WorkThread extends Thread {

	

	// 配置パラメーター

	downLoadParameter args;

	// 長さ

	int perLength;

	// offset

	int offset;

	int MAX_BUF = 1024;

	public WorkThread(downLoadParameter args, int perLength, int offset) {

		

		this.args = args;

		this.perLength = perLength;

		this.offset = offset;

		

	}

	

	public void run() {

		

		try {

			

			// 接続を作成する

			URL url = new URL(args.getDownLoadImageUrl());

	        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

			httpConnection.setRequestProperty("RANGE","bytes=" + offset + "-");

	        InputStream ins = httpConnection.getInputStream();

	        

	        String filePath = args.getSavePath() + File.separator + this.getName() + ".jpg";

	        

	        OutputStream bos = new FileOutputStream(new File(filePath), false);

	        byte[] buffer = new byte[MAX_BUF];

	        

	        int readSize;

            int size = 0;

            

            while ((readSize = ins.read(buffer)) != -1) {

            	

                size += readSize;

                if (size > perLength) {

                	

                	readSize = readSize - (size - perLength);

                    

                }

                

                bos.write(buffer, 0, readSize);

                

                if (size > perLength) {

                	

                    break;

                    

                }

                

            }

            

            bos.close();

            ins.close();

            

            args.compleThreadCount--;

			

		} catch (Exception e) {

			

			args.setCompleState(downLoadParameter.ERROR);

			

		}

		

	}

}

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import javax.swing.JOptionPane;

public class MergeFile extends Thread {

	

	downLoadParameter arg;

	int MAX_BUF = 1024;

	

	public MergeFile(downLoadParameter arg) {

		

		this.arg = arg;

	}

	

	public void run() {

		

		try {

			

			while(true) {

				

				if (arg.downLoadComple()) {

					

					break;

					

				} else {

					

					Thread.sleep(500);

					

				}

				

			}

			

			OutputStream output = new FileOutputStream(new File(arg.getSavePath() + File.separator + arg.getSaveName()), false);

			

			for (int i = 0; i < arg.getThreadCount(); i++) {

				

				String filePath = arg.getSavePath() + File.separator + "part" + i + ".jpg";

				

				File file = new File(filePath);

                InputStream is = new FileInputStream(file);

                

                byte[] buffer = new byte[MAX_BUF];

                int readSize;

                

                while ((readSize = is.read(buffer)) != -1) {

                	

                	output.write(buffer, 0, readSize);

                	

                }

                

                is.close();

                file.delete();

				

			}

			

			output.close();

			

			

//			if (downLoadParameter.ERROR.equals(parameter.getCompleState())) {

//				

//				JOptionPane.showMessageDialog(null, "ファイルの取得する操作際中でエラーが発生しました。");

//				

//			} else {

//				

//				JOptionPane.showMessageDialog(null, "成功しました");

//				

//			}

			

		} catch (Exception e) {

			

			arg.setCompleState(downLoadParameter.ERROR);

			

		}

		

	}

	

}