溫馨提示×

java怎么實現文件下載功能

小億
190
2024-04-08 09:56:39
欄目: 編程語言

在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對象。接著我們獲取輸入流并將其寫入到一個文件輸出流中,最后關閉輸入輸出流。這樣就實現了文件下載功能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女