Skip to content

方式一(适用于小型文件)

  • 代码示例

    java
    import java.io.FileOutputStream;
    import java.net.URL;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    
    public class FileDownloader {
        public static void downloadFile(String remoteFilePath, String localFilePath) {
            try {
                URL website = new URL(remoteFilePath);
                ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                FileOutputStream fos = new FileOutputStream(localFilePath);
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                fos.close();
                rbc.close();
                System.out.println("文件下载完成!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            downloadFile("https://example.com/file.pdf", "D:/file.pdf");
        }
    }

方式二(适用于大型文件)

  • 代码示例

    java
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class LargeFileDownloader {
        public static void downloadLargeFile(String downloadUrl, String savePath) {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                URL url = new URL(downloadUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(3000);
                connection.setRequestProperty("User-Agent", "Mozilla/4.0");
                inputStream = new BufferedInputStream(connection.getInputStream());
                File file = new File(savePath);
                if (file.exists()) file.delete();
                outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024 * 1024 * 5]; // 5MB 缓冲区
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                System.out.println("文件下载完成!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try { if (outputStream != null) outputStream.close(); } catch (IOException ignored) {}
                try { if (inputStream != null) inputStream.close(); } catch (IOException ignored) {}
            }
        }
        public static void main(String[] args) {
            downloadLargeFile("https://example.com/largefile.zip", "D:/largefile.zip");
        }
    }
  • 特点:使用缓冲流分块读取,适合大文件,避免一次性加载文件到内存导致内存溢出的问题

MIT版权,未经许可禁止任何形式的转载