在Java中,你可以使用InputStream
来下载大文件
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "https://example.com/largefile.zip";
String destinationFile = "downloaded_largefile.zip";
try {
downloadFile(fileUrl, destinationFile);
System.out.println("文件下载完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void downloadFile(String fileUrl, String destinationFile) throws Exception {
URL url = new URL(fileUrl);
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
ReadableByteChannel readableByteChannel = null;
try {
inputStream = new BufferedInputStream(url.openStream());
fileOutputStream = new FileOutputStream(destinationFile);
readableByteChannel = Channels.newChannel(inputStream);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = readableByteChannel.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
} finally {
if (readableByteChannel != null) {
try {
readableByteChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
这个示例中的downloadFile
方法接受一个文件URL和一个目标文件路径作为参数。它首先创建一个URL
对象,然后打开一个InputStream
。接下来,它创建一个FileOutputStream
和一个ReadableByteChannel
,并将InputStream
的内容读取到FileOutputStream
中。
没有搜到相关的文章