使用java读取 网站内容并写入本地文件中
首先使用URL 初始化请求地址
然后使用 url.openConnection() 打开连接
最后 初始化 输入流和输出流 来写内容
写入完成关闭输入、输出流
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
@Test
public void testUtils() throws IOException {
URL url = new URL("https://www.baidu.com");
URLConnection connection = url.openConnection();
InputStream io = connection.getInputStream();
OutputStream os = new FileOutputStream("aa.txt");
byte[] bytes = new byte[1024];
try {
int len = 0;
while ((len = io.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("error: " + e.getMessage());
} finally {
io.close();
os.close();
}
}