java http下载文件

2019-03-28  本文已影响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");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读