Java文件下载

public class UrlDown {
    public static void main(String[] args) throws Exception {

        // 下载地址
        URL url = new URL("https://m10.music.126.net/20201123142926/6c82578eccd898653a0fdd99de9f24c0/yyaac/0708/0652/0508/0b9b6827b718aa223af92bd52aa2424f.m4a");

        // 连接这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

        InputStream is = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("时间美好与你环环相扣.mp3");

        byte[] bytes = new byte[1024];
        int len;

        while ((len = is.read(bytes)) != -1) {
            fos.write(bytes, 0, len);
        }

        fos.close();
        is.close();
        urlConnection.disconnect();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的 Java 文件下载接口示例,供您参考: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileDownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = request.getParameter("filePath"); File file = new File(filePath); if (file.exists()) { ServletOutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[1024]; int len = 0; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); while ((len = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } fileInputStream.close(); outputStream.flush(); outputStream.close(); } else { response.sendError(404, "File not found!"); } } } ``` 在上述代码中,通过 `doGet()` 方法处理 GET 请求,并从请求参数中获取文件路径。如果文件存在,就获取文件流并循环向客户端输出文件内容,同时设置响应头和响应类型,使客户端浏览器弹出文件下载对话框,并以文件名命名下载文件。最后,记得在输出完毕后关闭文件流。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值