通过代码从网上下载一个图片及图片的复制

这是一个Java程序,演示了如何从网上下载一个图片并将其复制到本地文件系统。程序使用`URL`、`FileInputStream`、`FileOutputStream`和`BufferedInputStream`等类进行文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.test.http;


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;


public class HttpDemo {
static URL url=null;
public static void main(String[] args) throws IOException {
url= new URL("http://s11.sinaimg.cn/middle/0041w004ty6GuYCoqmu7a&690");
url();
copy(".\\aa.jpg");
}
//当前文件目录下的图片的拷贝
public static void copy(String name) throws IOException{
FileInputStream fil=new FileInputStream(name);
FileOutputStream fos=new FileOutputStream(".\\q.jpg");
byte[] by=new byte[1024];
while(true){
int read = fil.read(by);
if(read==-1){
break;
}else{
fos.write(by, 0, read);
}
}

//从网上下载一个图片到当前目录下
public static void url(){
InputStream openStream = null;
try {
openStream = url.openStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream("a.jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis=new BufferedInputStream(openStream);
byte[] by=new byte[10];
while (true) {
int read = 0;
try {
read = bis.read(by);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (read==-1) {
break;
}else{
try {
fos.write(by, 0, read);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值