温馨提示×

java怎么实现文件下载功能

小亿
82
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