天天看點

html中讀取多個檔案,用多線程讀取目錄中所有html檔案内容,求修正代碼

該樓層疑似違規已被系統折疊 隐藏此樓檢視此樓

public class AllThread extends Thread {

public String content = "";

public String url = "";

public void run() {

System.out.println(url);

content = getContents(url);

}

public AllThread(String the_url) {

url = the_url;

}

private static String getContents(String urlName) {

try {

StringBuffer sb = new StringBuffer();

URL url = new URL(urlName);

URLConnection u = url.openConnection();

InputStream is = u.getInputStream();

InputStreamReader isr = new InputStreamReader(is, "gbk");

int c;

while ((c = isr.read()) != -1) {

sb.append((char) c);

}

is.close();

isr.close();

return sb.toString();

} catch (IOException ex) {

return ex.getMessage();

}

}

public static void main(String args[]) {

//TODO自動生成方法存根

//String[] dir = {"http://www.baidu.com ", "http://www.yisou.com "}; File[] dir = new File("//192.168.18.232/heritrix/www.duote.com/softin").listFiles();//提取softin中所有的html檔案

AllThread[] threads = new AllThread[dir.length];

//循環輸出檔案名

for (int i = 0; i < dir.length; i++) {

threads[i] = new AllThread(dir[i].getName());

threads[i].start();

}

//循環輸出檔案内容

for (int i = 0; i < dir.length; i++) {

try {

threads[i].join();

} catch (InterruptedException e) {

// TODO 自動生成 catch 塊

e.printStackTrace(); }

System.out.println(threads[i].content);

}

}

}

輸出結果:31283.html3108.html53809.html22770.html42448.html11075.html22426.htmlno protocol: 2253.htmlno protocol: 19455.htmlno protocol: 26932.htmlno protocol: 21136.html…………………………(讀取檔案名成功,讀取内容卻失敗了TwT)