JAVA怎么下載大文件

小億
200
2023-08-25 04:44:32
欄目: 編程語言

您可以使用Java的URL類和URLConnection類來下載大文件。下面是一個(gè)簡(jiǎn)單的示例代碼:

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更改為要將文件保存到的路徑。然后運(yùn)行該代碼,它將從指定的URL下載文件并將其保存到本地。

0