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

📄 getfile.java

📁 上传工具的JAVA版本
💻 JAVA
字号:

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * 实现多线程下载
 */
class getFile extends Thread {

	int fileLength = 0; //文件大小

	int start = 0; //起点

	int end = 0; //终点

	URL url = null; //url

	String fileName; //文件名

	DataInputStream in; //数据输入流

	RandomAccessFile out; //随机读写流

	URLConnection conn;

	int tmpNum = 0;

	public getFile(int aStart, int aEnd, URL aUrl, String aFileName,
			String ThreadName) throws Exception {
		super(ThreadName);
		url = aUrl;
		fileName = aFileName;
		start = aStart;
		end = aEnd;
		conn = url.openConnection();
		conn.setRequestProperty("GET", "HTTP/1.1");
		conn.setRequestProperty("User-Agent", "xdj");
		conn.setRequestProperty("Accept", "*/*");
		conn.setRequestProperty("Accept-Language", "zh-cn");
		conn.setRequestProperty("Accept-Encoding", "gzip,defate");
		conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Range", "bytes=" + start + "-");
		conn.connect();
		fileLength = conn.getContentLength();
		in = new DataInputStream(conn.getInputStream());
		out = new RandomAccessFile(fileName, "rw");
		out.seek(start);
	}

	/**
	 * 线程入口
	 */
	public void run() {
		try {
			System.out.println(this.getName());
			writeFile();
		} catch (IOException e) {
			e.printStackTrace();

		} catch (IndexOutOfBoundsException ie) {
			System.out.println(this.getName() + "中start的值为:" + start);
			System.out.println("在" + this.getName() + "溢出");
			ie.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入文件
	 */
	private synchronized void writeFile() throws IOException {
		/**
		 * 添加一个文件指针测试:
		 */
		byte[] b = new byte[1024];
		int nRead = -1;
		int nAdd = 0;
		while ((nRead = in.read(b, 0, 1024)) > 0 && (start < end)) {
			out.write(b, 0, nRead);
			start += nRead;
		}		
		out.close();
		System.out.println(this.getName()+"下载完成!");
	}

	public void stopThread() {

	}

	/**
	 * 开启线程
	 */
	public void starThread() {
		this.start();
	}
}

⌨️ 快捷键说明

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