java IOUtils下载图片

 

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class ImgDownload {

    public static void main(String[] args) {
        downloadHttpUrl("https://www.baidu.com/img/bd_logo1.png", "D:/test/", "test.png");
    }

    public static String downloadHttpUrl(String url, String dir, String fileName) {  
        try {  
            URL httpurl = new URL(url);  
            File f = new File(dir + fileName);  
            FileUtils.copyURLToFile(httpurl, f);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
        return dir + fileName;  
    }  
    
    public static FileOutputStream openOutputStream(File file) throws IOException {  
        if (file.exists()) {  
            if (file.isDirectory()) {  
                throw new IOException("File '" + file + "' exists but is a directory");  
            }  
            if (file.canWrite() == false) {  
                throw new IOException("File '" + file + "' cannot be written to");  
            }  
        } else {  
            File parent = file.getParentFile();  
            if (parent != null && parent.exists() == false) {  
                if (parent.mkdirs() == false) {  
                    throw new IOException("File '" + file + "' could not be created");  
                }  
            }  
        }  
        return new FileOutputStream(file);  
    }  
    
    public static void copyURLToFile(URL source, File destination) throws IOException {  
        InputStream input = source.openStream();  
        try {  
            FileOutputStream output = openOutputStream(destination);  
            try {  
                IOUtils.copy(input, output);  
            } finally {  
                IOUtils.closeQuietly(output);  
            }  
        } finally {  
            IOUtils.closeQuietly(input);  
        }  
    }  
    
}

 

posted @ 2017-08-10 12:44  这个名字想了很久~  阅读(1423)  评论(0编辑  收藏  举报