zoukankan      html  css  js  c++  java
  • 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);  
            }  
        }  
        
    }
  • 相关阅读:
    穷举、迭代、以及while代替for循环的使用
    for循环与for循环嵌套
    day07 数据类型补充
    day06
    day05
    day04
    python2 和 python3 的区别
    day03
    第一周笔记
    day02笔记
  • 原文地址:https://www.cnblogs.com/shihaiming/p/7338673.html
Copyright © 2011-2022 走看看