File file (download the file in the HTTP path to the local)

/**
 * @author 阿杰
 * @effect 文件工具类 (将http文件下载到指定路径下)
 * @date 2022/4/24
 * @versions 1.0
 */
public class FileUtil {
    
    


    /**
     *  这个函数负责把获取到的InputStream流保存到本地。
     * @param imgUrl  图片http url
     * @param fileName  文件名称
     * @param filePath  文件要保存的路径
     * @return
     */
    public static boolean saveImageToDisk(String imgUrl, String fileName, String filePath) {
    
    
        InputStream inputStream = null;
        inputStream = getInputStream(imgUrl);//调用getInputStream()函数。
        byte[] data = new byte[1024];
        int len = 0;

        FileOutputStream fileOutputStream = null;
        try {
    
    
            fileOutputStream = new FileOutputStream(filePath + fileName);//初始化一个FileOutputStream对象。
            while ((len = inputStream.read(data))!=-1) {
    
    //循环读取inputStream流中的数据,存入文件流fileOutputStream
                fileOutputStream.write(data,0,len);
            }

        } catch (IOException e) {
    
    
            e.printStackTrace();
            return false;
        } finally{
    
    //finally函数,不管有没有异常发生,都要调用这个函数下的代码
            if(fileOutputStream!=null){
    
    
                try {
    
    
                    fileOutputStream.close();//记得及时关闭文件流
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
    
    
                try {
    
    
                    inputStream.close();//关闭输入流
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 将图片下载到本地
     * @param imgUrl  图片的url
     * @return 返回文件流
     */
    public static InputStream getInputStream(String imgUrl){
    
    
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
    
    
            URL url = new URL(imgUrl);//创建的URL
            httpURLConnection = (HttpURLConnection) url.openConnection();//打开链接
            httpURLConnection.setConnectTimeout(3000);//设置网络链接超时时间,3秒,链接失败后重新链接
            httpURLConnection.setDoInput(true);//打开输入流
            httpURLConnection.setRequestMethod("GET");//表示本次Http请求是GET方式
            int responseCode = httpURLConnection.getResponseCode();//获取返回码
            if (responseCode == 200) {
    
    //成功为200
                //从服务器获得一个输入流
                inputStream = httpURLConnection.getInputStream();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return inputStream;

    }

}

Guess you like

Origin blog.csdn.net/lijie0213/article/details/124380677