このチュートリアルでは、JavaでURLの内容を読み取る方法を説明します。 readというメソッドを作成します。このメソッドは、入力にStringを取り、URLのコンテンツを返します。 チュートリアルコードを実行してファイルをダウンロードするには、次の手順に従います。
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class ReadUrlContent {
public String read(String url) throws IOException {
// URLからストリームを開く
InputStream is = new URL(url).openStream();
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = is.read()) != -1) {
sb.append((char) cp);
}
// オブジェクトを文字列として返す
return sb.toString();
}
public static void main(String[] argv) {
ReadUrlContent example = new ReadUrlContent();
// URLの内容を読んでください。
String googleContent = "";
try {
googleContent = example.read("http://oliviertech.com/");
} catch (Exception e) {
e.printStackTrace();
}
int pos = googleContent.indexOf( "oliviertech" );
// 出力にコンテンツを表示します。
System.out.println(googleContent.substring(pos, pos+20));
}
}
oliviertech.com" typ
oliviertechの最初のインスタンスの後にStringに返されるテキスト