
Лаб. 8 Java (Вариант 3)
.docx
a)
package lab_3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.MalformedURLException;
public class WebPageReader {
public static void main(String[] args) {
BufferedReader reader = null;
URL url = null;
String https = "https://"; //Идентификатор протокола
String urlAddress = "www.example.com"; //Имя ресурса
try {
url = new URL(https+urlAddress);
}
catch (MalformedURLException e) {
System.out.println(e.getMessage());
}
try {
if (url != null) {
//Создание буфера для чтения исходного кода веб-страницы
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); //Вывод строк на консоль
}
}
} catch (IOException e) {
e.printStackTrace(); //Исключение ввода-вывода
} catch (NullPointerException e) {
e.printStackTrace(); //Исключение при нулевой ссылке
}finally {
if (reader != null) {
try {
reader.close(); //Закрытие буфера
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
b)
package lab_3;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class FTPFileDownloader {
public static void main(String[] args) {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
String remoteFilePath = "ftp://ftp.univer.omsk.ru/pub/rfc/rfc1396.txt";
String localFilePath = "FTP.txt";
URL url = new URL(remoteFilePath);
URLConnection connection = url.openConnection(); //Установка соединения с сервером
inputStream = connection.getInputStream(); //Получение потока для чтения содержимого файла с сервера
outputStream = new FileOutputStream(localFilePath); //Создание потока для записи в файл
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead); //Запись прочитанных данных в файл
}
System.out.println("Файл успешно скачан.");
} catch (IOException e) {
e.printStackTrace(); //Исключение ввода-вывода
} finally {
try {
if (outputStream != null) {
outputStream.close(); //Закрытие потока вывода
}
if (inputStream != null) {
inputStream.close(); //Закрытие потока ввода
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}