[size=large]代码例子:[/size]
package com.test;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class URLConnectionTest
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://www.infoq.com");
InputStream in = url.openStream();
OutputStream os = new FileOutputStream("C:/3.txt");
byte[] buffer = new byte[2048];
int length = 0;
while (-1 != (length = in.read(buffer, 0, buffer.length)))
{
//String str = new String(buffer,0,length);
// System.out.println(str);
os.write(buffer,0,length);
}
os.close();
in.close();
}
}
本文介绍了一个简单的Java程序,该程序利用URLConnection从指定URL抓取网页内容并将其保存到本地文件中。通过创建URL对象并调用openStream()方法读取输入流,再将输入流写入到本地文件。
965

被折叠的 条评论
为什么被折叠?



