美文网首页
java http下载文件

java http下载文件

作者: 行走的鸡汤哥 | 来源:发表于2019-03-28 00:01 被阅读0次

网络文件下载:支持txt、jpg、zip等格式的文件

@Slf4j
public class FileHelper {

    private FileHelper() {
        
    }

    public static void main(String[] args) throws IOException {
        File file = new File("E:\\tmp\\image.jpg");
        String downloadUrl = "http://image.zzd.sm.cn/1560454273033615458.jpg";
        downloadZip(downloadUrl, file);
    }

    private static void downloadZip(String downloadUrl, File file) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            URL url = new URL(downloadUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, length);
            }
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            log.error("download error ! url :{}, exception:{}", downloadUrl, e);
        }
        System.out.println("end");
    }
}

相关文章

网友评论

      本文标题:java http下载文件

      本文链接:https://www.haomeiwen.com/subject/pyaxbqtx.html