Java多线程的批文件下载实例

 以下是根据指定的URL下载一批文件,使用多线程可以尽量提高下载效率,这只是多线程的简单运用实例,后期有空我会介绍Java多线程的一些挑战性实例!

//使用多线程下载文件
public class FileDownloaderApp {
	public static void main(String[] args) {
		String[] urls = new String[10];
		urls[1] = "https://goss.veer.com/creative/vcg/veer/800water/veer-153618676.jpg";
		urls[2] = "https://goss.veer.com/creative/vcg/veer/800water/veer-133825919.jpg";
		urls[3] = "https://goss.veer.com/creative/vcg/veer/800water/veer-134847228.jpg";
		urls[4] = "https://goss.veer.com/creative/vcg/veer/800water/veer-157769759.jpg";
		urls[5] = "https://goss.veer.com/creative/vcg/veer/800water/veer-135319267.jpg";
		urls[0] = "https://goss.veer.com/creative/vcg/veer/800water/veer-159067221.jpg";
		urls[6] = "https://goss.veer.com/creative/vcg/veer/800water/veer-153474994.jpg";
		urls[7] = "https://goss.veer.com/creative/vcg/veer/800water/veer-134179826.jpg";
		urls[9] = "https://goss.veer.com/creative/vcg/veer/800water/veer-146031982.jpg";
		urls[8] = "https://goss.veer.com/creative/vcg/veer/800water/veer-159017302.jpg";
		// 多线程下载
		Thread downloaderThread = null;
		for (String url : urls) {
			// 创建文件下载器线程
			downloaderThread = new Thread(new FileDownloader(url));
			// 启动文件下载器线程
			downloaderThread.start();
			
		}

	}

	// 文件下载器
	static class FileDownloader implements Runnable{
		private final String fileURL;

		public FileDownloader(String fileURL) {
			this.fileURL = fileURL;
		}

		// 从指定的URL下载文件,并将其保存到指定的输出流中
		private void downloadFile(URL url, OutputStream outputStream, int bufSize) throws IOException {
			URLConnection connection = url.openConnection();
			// 以Post方式提交表单,默认get方式
			connection.setDoInput(true);
			connection.setDoOutput(true);
			// post方式不能使用缓存
			connection.setUseCaches(false);
			// 连接指定的资源
			connection.connect();
			// 获取网络输入流
			InputStream inputStream = connection.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(inputStream);

			BufferedOutputStream bos = new BufferedOutputStream(outputStream);
			byte[] buff = new byte[bufSize];
			try {
				int i = 0;
				while ((i = bis.read(buff)) != -1) {
					bos.write(buff, 0, i);
					bos.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		@Override
		public void run() {
			System.out.println("Downloading from " + fileURL);
			String fileBaseName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
			try {
				URL url = new URL(fileURL);
				String localFileName = "E:/img" + "/viscent-" + fileBaseName;
				System.out.println("Save to: " + localFileName);
				downloadFile(url, new FileOutputStream(localFileName), 1024);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

 

你可能感兴趣的:(多线程,文件下载)