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 и прочитать текст из него.URL-адрес * может быть указан в командной строке.Если аргумент командной строки не указан, * пользователю предлагается ввести данные.Это может быть полный 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