Java将URL转为File


将一个URL转为File

    @GetMapping("/getUrlFile")
    @ResponseBody
    public void getUrlFile() {
        InputStream is = null;
        File file = null;
        OutputStream os = null;
        String urlPath = "https://img1.clozhome.com/new-clozhome/crm/cohort_pay.jpg";
        String[] split = urlPath.split("/");
        String fileName = split[split.length - 1];

        try {
            file = new File("D:\\BaiduYunDownload\\" + fileName);
            URL urlfile = new URL(urlPath);
            is = urlfile.openStream();
            os = new FileOutputStream(file);

            // 开始存储文件
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } catch (Exception e) {

        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

声明:冰醋酸|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - Java将URL转为File


一切随缘