java怎么实现文件下载功能

avatar
作者
筋斗云
阅读量:0

在Java中可以通过使用URLConnection类来实现文件下载功能。以下是一个简单的示例代码:

import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection;  public class FileDownload {      public static void main(String[] args) {         String fileUrl = "http://example.com/file.zip";         String outputFilePath = "file.zip";          try {             URL url = new URL(fileUrl);             URLConnection conn = url.openConnection();             InputStream inputStream = conn.getInputStream();              FileOutputStream outputStream = new FileOutputStream(outputFilePath);              byte[] buffer = new byte[4096];             int bytesRead = -1;              while ((bytesRead = inputStream.read(buffer)) != -1) {                 outputStream.write(buffer, 0, bytesRead);             }              outputStream.close();             inputStream.close();              System.out.println("File downloaded successfully!");         } catch (Exception e) {             e.printStackTrace();         }     } } 

在这个示例中,我们首先创建一个URL对象,然后通过调用openConnection()方法获取URLConnection对象。接着我们获取输入流并将其写入到一个文件输出流中,最后关闭输入输出流。这样就实现了文件下载功能。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!