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);  
            }  
        }  
        
    }
  • 相关阅读:
    待学习资料
    Hive之数据类型
    Hive 之元数据库的三种模式
    Hive之数据模型
    311 jvm类加载以及对象回收相关
    221 netty模型相关
    J101
    213 NIO编程
    XXLJOB终止定时任务的犯二小故事
    XXL-JOB源码研究(1)---version 2.1.2
  • 原文地址:https://www.cnblogs.com/shihaiming/p/7338673.html
Copyright © 2011-2022 走看看