import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class URLExample {
public static void main(String[] args) {
try {
// 创建一个URL对象
URL url = new URL("https://example.com/textfile.txt");
// 打开URL连接
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
// 读取并显示文本文件的内容
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
// 关闭缓冲区
in.close();
} catch (MalformedURLException e) {
// 如果URL格式有误,会抛出MalformedURLException异常
System.err.println("URL格式错误: " + e.getMessage());
} catch (IOException e) {
// 如果发生I/O错误,会抛出IOException异常
System.err.println("读取URL内容时发生错误: " + e.getMessage());
}
}
}