模拟下载某个文件

@SuppressWarnings("resource")
@Test
public void test() throws Exception{
//表示的是一个URL地址
URL url = new URL("http://192.168.10.150:8080/txt/hello.html");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());

//打开一个连接
URLConnection openConnection = url.openConnection();
//URLConnection转成HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) openConnection;
//连接服务器
conn.connect();

int responseCode = conn.getResponseCode();
//连接服务器成功
if(responseCode == 200){
//获取输入流
InputStream is = conn.getInputStream();
//创建输出流
FileOutputStream fos = new FileOutputStream("123.txt");
//一边读一边写
byte[] b = new byte[100];
int len = 0;
while((len  = is.read(b)) != -1){
fos.write(b, 0, len);
}
//关闭流
fos.close();
is.close();
}
}

你可能感兴趣的:(IO流,网络编程)