在Java中下载大文件时,为了避免内存溢出,可以使用以下方法:
InputStream inputStream = new BufferedInputStream(new FileInputStream("largeFile.txt"));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("output.txt"));
RandomAccessFile file = new RandomAccessFile("largeFile.txt", "r");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); // 分配1MB的缓冲区
while (channel.read(buffer) != -1) {
buffer.flip(); // 切换到读模式
// 处理数据
buffer.compact(); // 切换到写模式
}
channel.close();
file.close();
int bufferSize = 1024 * 1024; // 1MB
URL url = new URL("http://example.com/largeFile.txt");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int fileSize = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream("output.txt");
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
totalBytesRead += bytesRead;
outputStream.write(buffer, 0, bytesRead);
// 可以在这里更新下载进度
}
outputStream.close();
inputStream.close();
connection.disconnect();
int numThreads = 4;
int bufferSize = 1024 * 1024; // 1MB
URL url = new URL("http://example.com/largeFile.txt");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int fileSize = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream("output.txt");
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytesRead = 0;
List<DownloadThread> threads = new ArrayList<>();
for (int i = 0; i < numThreads; i++) {
long start = i * fileSize / numThreads;
long end = (i + 1) * fileSize / numThreads;
DownloadThread thread = new DownloadThread(url, start, end, buffer, outputStream);
threads.add(thread);
thread.start();
}
for (DownloadThread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
outputStream.close();
inputStream.close();
connection.disconnect();
这些方法可以结合使用,以实现高效且内存友好的大文件下载。