使用JavaIO提供的API下載指定文件(image)

</pre><pre name="code" class="java">
使用JavaIO提供的API下載指定文件(image)

package com.net.download;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * ClassName:Test.java
 * @author xg.qiu
 * @since JDK1.7
 * Aug 26, 2015
 * 使用JavaIO提供的API下載指定文件(image)
 */
public class DownLoad {
	
	public static void main(String[] args) {
		// 調用封裝好的方法
		download("http://static.oschina.net/uploads/user/500/1000631_50.jpg", "E:/download.jpg");
	}
	
	/**
	 * 封裝了用戶傳參的方法
	 * @author xg.qiu<br/>
	 * @since  JDK 1.7
	 * @time   Aug 31, 2015
	 * @param imgUrl 網絡上的圖片路徑地址
	 * @param newImg 保存在本機上的圖片路徑地址
	 */
	public static void download(String imgUrl,String newImg){
		try {
			//1.創建一個URL
			URL url = new URL(imgUrl);
			//2.使用數據輸入流獲取URL信息
			DataInputStream data = new DataInputStream(url.openStream());
			int dataLength = data.available();
			//3.創建一個文件輸出流,將網絡流輸出到文件流
			File newFile = new File(newImg);
			FileOutputStream output = new FileOutputStream(newFile);
			byte [] buffer = new byte[1024];
			int len;
			// 4.循環讀取並寫入文件流
			while((len = data.read(buffer)) != -1 ){
				output.write(buffer,0,len);
			}
			//關閉網絡流
			data.close();
			//關閉文件流
			output.close();
			if(newFile.length() == dataLength){
				System.out.println("文件下載成功.");
			}else{
				System.out.println("文件下載失敗.");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


發佈了32 篇原創文章 · 獲贊 10 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章