本教程介紹如何在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);
}
// 將Object作為String返回
return sb.toString();
}
public static void main(String[] argv) {
ReadUrlContent example = new ReadUrlContent();
// 閱讀網址內容。
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中返回的文本
java從url讀取文本文件