温馨提示×

JAVA怎么下载大文件

小亿
208
2023-08-25 04:44:32
栏目: 编程语言

您可以使用Java的URL类和URLConnection类来下载大文件。下面是一个简单的示例代码:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) {
String fileURL = "http://example.com/largefile.zip";
String savePath = "/path/to/save/directory/largefile.zip";
try {
URL url = new URL(fileURL);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
bufferedInputStream.close();
System.out.println("文件下载完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

您只需将fileURL更改为要下载的文件的URL,将savePath更改为要将文件保存到的路径。然后运行该代码,它将从指定的URL下载文件并将其保存到本地。

0