在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();
這些方法可以結合使用,以實現高效且內存友好的大文件下載。