java实现多线程下载(一)

2014-11-24 08:49:19 · 作者: · 浏览: 0
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 = downlodeJTextFiel
d.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"); //