import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/ ** *此简短程序通过以下示例演示了URL和URLConnection类 *尝试打开与URL的连接并从中读取文本。网址可以 *在命令行上指定。如果未提供命令行参数, *提示用户输入。它可以是完整的网址,包括 *以“ protocol”开头(“ http://”,“ ftp://”或“ file://”)。如果有 *不是以这些协议之一开头,而是将“ http://”添加到 *输入行。如果尝试获取数据时发生错误,则会显示一条消息 *输出。否则,URL中的文本将复制到屏幕上。 * /
public class FetchURL {
public static void main(String[] args) {
String url; // The url from the command line or from user input.
url = "http://sites.google.com/site/stephenkofflercodingprojects/"
+ "files-to-download/CBS 20181223 PAGEVIEWS.TXT";
System.out.println();
try {
readTextFromURL(url);
} catch (IOException e) {
System.out.println("\n*** Sorry, an error has occurred ***\n");
System.out.println(e);
System.out.println();
}
}
/**
* This subroutine attempts to copy text from the specified URL onto the
screen.
* Any error must be handled by the caller of this subroutine.
*
* @param urlString contains the URL in text form
*/
static void readTextFromURL(String urlString) throws IOException {
/*
* Open a connection to the URL, and get an input stream for reading
data from
* the URL.
*/
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
InputStream urlData = connection.getInputStream();
/*
* Check that the content is some type of text. Note: If
getContentType() method
* were called before getting the input stream, it is possible for
contentType
* to be null only because no connection can be made. The
getInputStream()
* method will throw an error if no connection can be made.
*/
String contentType = connection.getContentType();
System.out.println("Stream opened with content type: " + contentType);
System.out.println();
if (contentType == null || contentType.startsWith("text") == false)
throw new IOException("URL does not seem to refer to a text file.");
System.out.println("Fetching context from " + urlString + " ...");
System.out.println();
/*
* Copy lines of text from the input stream to the screen, until end-of-
file is
* encountered (or an error occurs).
*/
BufferedReader in; // For reading from the connection's input stream.
in = new BufferedReader(new InputStreamReader(urlData));
while (true) {
String line = in.readLine();
if (line == null)
break;
System.out.println(line);
}
in.close();
} // end readTextFromURL()
} // end class FetchURL