java下载资源到本地

可下载图片、jar包、以及各种文件

import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import java.security.SecureRandom;


public class Filedownload {

    public static void main(String[] args) {
        String fileUrl = "http://192.168.1.88:6008/agent/RichsyncAgent/x86/RichsyncAgent-177-2024_04_11_beta.tar";  // 替换为要下载的文件的URL
        String fileSuffix = fileUrl.substring(fileUrl.lastIndexOf("."));
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + fileSuffix;
        File outputPath = new File("D:\\file\\"+finalFileName); //保存到本地的文件路径
        try {
            File dir = outputPath.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            outputPath.createNewFile();//创建文件
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                FileOutputStream outputStream = new FileOutputStream(outputPath);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                inputStream.close();
                System.out.println("下载文件成功,目录:" + outputPath);
            } else {
                System.out.println("下载文件失败,错误码:" + connection.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值