java大文件断点续传实现代码
以下是一个基本的Java大文件断点续传实现代码,使用RandomAccessFile类。
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownload {
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
String fileURL = "http://example.com/file.zip";
String saveDir = "C:/downloads/";
String fileName = "file.zip";
int numThreads = 4;
try {
URL url = new URL(fileURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
int fileSize = conn.getContentLength();
System.out.println("File size: " + fileSize);
File file = new File(saveDir + fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(fileSize);
int chunkSize = fileSize / numThreads;
for (int i = 0; i < numThreads - 1; i++) {
new DownloadThread(i * chunkSize, (i + 1) * chunkSize - 1, fileURL, saveDir + fileName).start();
}
new DownloadThread((numThreads - 1) * chunkSize, fileSize - 1, fileURL, saveDir + fileName).start();
conn.disconnect();
} else {
System.out.println("Error: Server returned HTTP response code " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class DownloadThread extends Thread {
private int startByte;
private int endByte;
private String fileURL;
private String saveFilePath;
public DownloadThread(int startByte, int endByte, String fileURL, String saveFilePath) {
this.startByte = startByte;
this.endByte = endByte;
this.fileURL = fileURL;
this.saveFilePath = saveFilePath;
}
@Override
public void run() {
try {
URL url = new URL(fileURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes=" + startByte + "-" + endByte);
byte[] buffer = new byte[BUFFER_SIZE];
RandomAccessFile raf = new RandomAccessFile(saveFilePath, "rw");
raf.seek(startByte);
int bytesRead;
while ((bytesRead = conn.getInputStream().read(buffer)) != -1) {
raf.write(buffer, 0, bytesRead);
}
conn.disconnect();
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
参考文章:http://blog.ncmem.com/wordpress/2023/10/27/java%e5%a4%a7%e6%96%87%e4%bb%b6%e6%96%ad%e7%82%b9%e7%bb%ad%e4%bc%a0%e5%ae%9e%e7%8e%b0%e4%bb%a3%e7%a0%81/
欢迎入群一起讨论