Java 代码视频下载
时间: 2024-09-19 15:12:24 浏览: 32
视频网站代码 java视频网站代码
在Java中下载视频文件通常涉及到网络请求和文件操作。你可以使用像`java.net.URL`、`HttpURLConnection`或更现代的库如`Apache HttpClient`来进行HTTP请求获取视频流,然后使用`java.io.FileOutputStream`将其保存到本地。以下是一个简单的示例,展示如何使用`HttpURLConnection`下载视频:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class VideoDownloader {
public static void downloadVideo(String videoUrl, String savePath) throws IOException {
URL url = new URL(videoUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int contentLength = connection.getContentLengthLong();
byte[] buffer = new byte[4096];
long totalDownloaded = 0;
FileOutputStream outputStream = new FileOutputStream(savePath);
try {
while (totalDownloaded < contentLength) {
int bytesRead = connection.getInputStream().read(buffer);
if (bytesRead == -1) break; // End of stream
outputStream.write(buffer, 0, bytesRead);
totalDownloaded += bytesRead;
System.out.println("Downloaded " + totalDownloaded + " bytes.");
}
} finally {
outputStream.close();
connection.disconnect();
}
System.out.println("Video downloaded successfully to " + savePath);
}
}
```
阅读全文