`
u011936142
  • 浏览: 43267 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

java实现多线程下载

 
阅读更多
package donghongyujava.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.plaf.InsetsUIResource;

public class DownlodeJframe_v2 extends JFrame {
	private JLabel downlodeJlabel;
	private JTextField downlodeJTextField;
	private JButton downlodeJButton;

	public DownlodeJframe_v2() {
		super("下载页面");
		this.setLayout(null);
		downlodeJlabel = new JLabel("下载连接:");
		downlodeJlabel.setBounds(20, 30, 80, 30);

		downlodeJTextField = new JTextField(
				"http://172.22.65.22:8080/day31/vedio/test.rmvb");
		downlodeJTextField.setBounds(90, 30, 350, 30);

		downlodeJButton = new JButton("立即下载");
		downlodeJButton.setMargin(new InsetsUIResource(0, 0, 0, 0));
		downlodeJButton.setBounds(200, 120, 100, 40);

		add(downlodeJlabel);
		add(downlodeJTextField);
		add(downlodeJButton);

		downlodeJButton.addActionListener(new MyActionListener());

		this.setSize(500, 300);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);

	}

	public static void main(String[] args) {
		new DownlodeJframe_v2();
	}

	// 事件监听的内部类
	class MyActionListener implements ActionListener {

		// 声明随机访问的随机访问文件
		private RandomAccessFile access;

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			// 设置按钮不可用
			downlodeJButton.setEnabled(false);
			// 获取下载链接
			final String path = downlodeJTextField.getText();
			try {
				// 根据路径创建url对象的对象
				URL url = new URL(path);
				// HttpURLConnection支持 HTTP 特定功能的 URLConnection。
				/*
				 * 每个 HttpURLConnection 实例都可用于生成单个请求, 但是其他实例可以透明地共享连接到 HTTP
				 * 服务器的基础网络。 请求后在 HttpURLConnection 的 InputStream 或 OutputStream
				 * 上 调用 close() 方法可以释放与此实例关联的网络资源, 但对共享的持久连接没有任何影响。如果在调用
				 * disconnect() 时持久连接空闲,则可能关闭基础套接字。
				 */
				// 调用url中的openConnection(Proxy proxy)与 openConnection() 类似,
				// 所不同是连接通过指定的代理建立;不支持代理方式的协议处理程序将忽略该代理参数并建立正常的连接。
				HttpURLConnection httpURLConnection = (HttpURLConnection) url
						.openConnection();

				// 获取目标资源的大小
				int size = httpURLConnection.getContentLength();
				// 获取目标资源的名称并设置对应的保存名称
				// substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串
				// /该子字符串从指定索引处的字符开始,直到此字符串末尾。
				// lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。
				File file = new File("E:"
						+ path.substring(path.lastIndexOf("/")));
				// 根据文件的名称创建出RandomAccessFile此类的实例支持对随机访问文件的读取和写入。
				// RandomAccessFile(File file, String mode) 创建从中读取和向其中写入
				// (可选)的随机访问文件流,该文件由 File 参数指定。
				// mode取值:
				/*
				 * 值 含意
				 * 
				 * "r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。 "rw"
				 * 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。 "rws" 打开以便读取和写入,对于
				 * "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。 "rwd" 打开以便读取和写入,对于
				 * "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。
				 */

				access = new RandomAccessFile(file, "rw");
				// 设置文件的大小
				access.setLength(size);
				// 关闭此随机访问文件流并释放与该流关联的所有系统资源。
				access.close();
				// 指示近期服务器不太可能有其他请求。
				httpURLConnection.disconnect();

				// 定义线程的数量
				int threadNumber = 3;
				// 向创建出来的与目标文件大小及类型相同的文件中写入数据
				for (int i = 1; i <= threadNumber; i++) {
					// 根据目标资源的总大小计算每条线程所需要分担的下载大小
					int blockSize = size / threadNumber;
					// 计算出每条线程的开始下载位置
					final int startSize = (i - 1) * blockSize;

					int temp = i * blockSize - 1;
					// 判断当前运行的线程是不是最后一条
					if (i == threadNumber) {
						if (temp < size) {
							temp = size;
						}
					}
					// 计算线程下载的结束位置
					final int endSize = temp;

					// 创建线程内部的文件随机读取的对象
					final RandomAccessFile threadFile = new RandomAccessFile(file,
							"rw");

					// 创建线程
					new Thread() {
						public void run() {
							// 创建与资源文件的在一次连接
							try {
								// 根据目标资源的路径创建url对象
								URL url = new URL(path);
								// 打开链接
								HttpURLConnection httpURLConnection = (HttpURLConnection) url
										.openConnection();
								// 设置一般请求属性。
								httpURLConnection.setRequestProperty("Range",
										"bytes=" + startSize + "-" + endSize);
								// 获取连接后的输入流对象
								InputStream is = httpURLConnection
										.getInputStream();
								// 设置文件开始写入的位置
								threadFile.seek(startSize);
								//缓冲区创建
								byte buffer[]=new byte[1024];
								//读取文件长度
								int len=0;
								while((len=is.read(buffer))!=-1){
									threadFile.write(buffer, 0, len);
								}
								//释放资源
								is.close();
								threadFile.close();
								httpURLConnection.disconnect();
															

							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					}.start();

				}

			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics