標籤:void ace file 位元組數組 connect htm 網路資源 tac 檔案儲存體
Http01App.java
1.使用了多線程、io流,net(網路包)
package main;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by lxj-pc on 2017/6/27.
*/
public class Http01App {
public static void main(String[] args) {
String url = "http://tuijian.hao123.com:80/index.html";
//啟動線程下載指定位置的html內容
new Thread(new DownloadHtmlTask(url)).start();
//下載指定的html內容,並存在d://html/hao123.html
}
static class DownloadHtmlTask implements Runnable {
private String url;
String fileName = "hao123.html";
String dirPath = "d:/lxj";
public DownloadHtmlTask(String url) {
this.url = url;
}
@Override
public void run() {
//下載url指定的HTMl網頁內容
try {
URL htmlURL = new URL(url);
//開啟網路資源串連
try {
URLConnection urlConnection = htmlURL.openConnection();//.filed
HttpURLConnection conn = (HttpURLConnection) urlConnection;
//擷取網路資源的讀取流
InputStream is = conn.getInputStream();
//判斷網路資源響應是否成功
if (conn.getResponseCode() == 200) {
//記憶體流 ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[20 * 1024];//每次讀取最大記憶體大小20k,緩衝大小
int len = -1; //每次讀取的位元組長度
//開始讀取網路資料
//檢測檔案下載的進度
//1.擷取網路資源的總長度
int contentLength = conn.getContentLength();
//2.聲明當前已讀取的資源長度,累加len
int curLen = 0;
while ((len = is.read(buffer)) != -1) {
//將讀取的資料讀取寫入記憶體流中
baos.write(buffer, 0, len);
//3.計算下載進度
curLen += len;
System.out.println(curLen + " " + contentLength);
//4.計算下載進度
int p = curLen / contentLength;
System.out.println("下載進度" + p + "%");
}
//下載完成,擷取記憶體流中的資料
byte[] bytes = baos.toByteArray();
//將位元組數組轉成字串,並列印到控制台
// "hello".getBytes(); zifu->zijie
String htmlContent = new String(bytes, "utf-8");
writerFile(htmlContent, dirPath, fileName);//成員方法在下面
System.out.println(htmlContent);
// System.out.println(htmlContent);
}} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
//將檔案儲存體在指定的path的檔案中
private void writerFile(String htmlContent, String dirPath, String fileName) {
File dir = new File(dirPath);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(new File(dir, fileName));
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(htmlContent);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void outputFile(String content,String dirPath,String fileName){
File dir=new File(dirPath);
try {
FileOutputStream fileOutputStream=new FileOutputStream(new File(dir,fileName));
fileOutputStream.write(content.getBytes("utf-8"));
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
簡單爬蟲 從指定地址下載網站內容