java网络编程____使用url下载远程文件(图片,软件等)

package com.test.net.utils;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

/**
 * @author God
 * url工具类下载文件
 */
public class URLReader {
	//发现要比httpurl下载要快的多呵呵
	public static void main(String[] args) throws Exception {
		//下载一个图片
		//String urlpath = "https://img6.bdstatic.com/img/image/smallpic/1.jpg";
		//下载一个qq旋风软件
		String urlpath ="http://dldir1.qq.com/invc/cyclone/QQDownload_Setup_48_773_400.exe";
		URL url = new URL(urlpath);
		//url的基本函数
		System.out.println(url.getAuthority());
		System.out.println(url.getContent());
		System.out.println(url.getDefaultPort());
		System.out.println(url.getHost());
		System.out.println(url.getPath());
		System.out.println(url.getPort());
		System.out.println(url.getProtocol());
		//下在资源
		DataInputStream dataInputStream = new DataInputStream(url.openStream());
		FileOutputStream fileOutputStream = new FileOutputStream(new File(getStrName(urlpath)));
		byte[] bytes = new byte[1024];
		int length = 0;
		while ((length = dataInputStream.read(bytes)) != -1) {
			fileOutputStream.write(bytes, 0, length);
			System.out.println("下载中....");
		}
		System.out.println("下载完成...");
		dataInputStream.close();
		fileOutputStream.close();
	}

	public static String getStrName(String url) {
		String[] sarry = url.split("/");
		return sarry[sarry.length - 1];
	}

}

//

java网络编程____使用url下载远程文件(图片,软件等)_第1张图片

//

java网络编程____使用url下载远程文件(图片,软件等)_第2张图片

 

你可能感兴趣的:(JavaEE核心)