您的位置:首页 > 编程语言

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

2017-03-31 15:33 447 查看
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();
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐