java如何实现文件下载功能

2024-04-12

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

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class FileDownload {
    public static void main(String[] args) {
        String fileUrl = "http://example.com/file.txt";
        String savePath = "downloaded_file.txt";

        try {
            URL url = new URL(fileUrl);
            URLConnection conn = url.openConnection();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            FileOutputStream out = new FileOutputStream(savePath);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            out.close();
            in.close();
            System.out.println("File downloaded successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们首先创建一个URL对象,然后通过URLConnection打开连接并获取输入流。接着创建一个输出流,并使用循环来读取输入流中的数据并写入输出流中,直到读取完整个文件。最后关闭输出流和输入流,并输出下载成功的提示。