建立工具類:
package com.blueZhang;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class Demo4 {// 擷取伺服器端資源的位元組輸入資料流public static InputStream getInputStream(String path) {//URL url;//try {url = new URL(path);//HttpURLConnection conn = (HttpURLConnection) url.openConnection();//conn.setRequestMethod("GET");//conn.setConnectTimeout(5000);//conn.setDoInput(true);//if (conn.getResponseCode() == 200) {//InputStream is = conn.getInputStream();return is;}} catch (Exception e) {e.printStackTrace();}return null;}// 讀取伺服器端的資源public static void writeToFile(InputStream input) {//FileOutputStream fos = null;//try {//fos = new FileOutputStream("file/1.txt");//byte[] arr = new byte[1024];//int len = 0;//while ((len = input.read(arr)) != -1) {//fos.write(arr, 0, len);//fos.flush();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {if (input != null) {try {input.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (fos != null) {try {fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public static void main(String[] args) {}}
建立測試類別
package com.blueZhang;import java.io.InputStream;public class Test {/** * @param args */public static void main(String[] args) {String path = "http://news.xinhuanet.com/ttgg/2015-08/23/c_1116344298.htm";InputStream in = HttpUtils.getInputStream(path);HttpUtils.writeToFile(in);}}