新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

JAVA怎样下载大文件,java下载文件

发布时间:2023-08-28 08:00:00

JAVA怎样下载大文件

您可使用Java的URL类和URLConnection类来下载大文件。下面是一个简单的示例代码:
```java
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)) != ⑴) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
bufferedInputStream.close();
System.out.println("文件下载完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
您只需将`fileURL`更改成要下载的文件的URL,将`savePath`更改成要将文件保存到的路径。然后运行该代码,它将从指定的URL下载文件并将其保存到本地。