目前我正在研究一個可以用來讀取由url指定的網站內容的類。我只是用java.io
和java.net
開始我的冒險,所以我需要諮詢我的設計。將網站內容讀入字符串
用法:
TextURL url = new TextURL(urlString);
String contents = url.read();
我的代碼:
package pl.maciejziarko.util;
import java.io.*;
import java.net.*;
public final class TextURL
{
private static final int BUFFER_SIZE = 1024 * 10;
private static final int ZERO = 0;
private final byte[] dataBuffer = new byte[BUFFER_SIZE];
private final URL urlObject;
public TextURL(String urlString) throws MalformedURLException
{
this.urlObject = new URL(urlString);
}
public String read()
{
final StringBuilder sb = new StringBuilder();
try
{
final BufferedInputStream in =
new BufferedInputStream(urlObject.openStream());
int bytesRead = ZERO;
while ((bytesRead = in.read(dataBuffer, ZERO, BUFFER_SIZE)) >= ZERO)
{
sb.append(new String(dataBuffer, ZERO, bytesRead));
}
}
catch (UnknownHostException e)
{
return null;
}
catch (IOException e)
{
return null;
}
return sb.toString();
}
//Usage:
public static void main(String[] args)
{
try
{
TextURL url = new TextURL("http://www.flickr.com/explore/interesting/7days/");
String contents = url.read();
if (contents != null)
System.out.println(contents);
else
System.out.println("ERROR!");
}
catch (MalformedURLException e)
{
System.out.println("Check you the url!");
}
}
}
我的問題是: 是否達到我想要有什麼好辦法?有沒有更好的解決方案?
我特別不喜歡sb.append(new String(dataBuffer, ZERO, bytesRead));
,但我無法用其他方式表達。每次迭代創建一個新的字符串是否好?我想不。
還有其他弱點嗎?
在此先感謝!
謝謝。我喜歡URLConnection!我想我應該在我的項目中使用它。 – 2011-05-03 10:41:21
我接受了你的回答。有用! – 2011-05-03 10:53:26
請注意,應該使用con.getContentType()而不是'con.getContentEncoding()',但它返回類似於「」text/html; charset = UTF-8「'的名稱,所以必須按順序解析該值以提取實際的編碼(我已經添加了對上面的代碼的評論,以反映這一點) – xav 2016-08-16 19:48:15