Java根据URL路径将网络视频保存到本地
功能思路
前段时间做了一个网络视频上传到腾讯云的一个需求,我这个小学生的思路就是先把网络视频保存到本地,在获取本地保存的视频上传到云上,看的是真的啰嗦,但是技穷只会这样了。
代码实现:
/**
* 保存到本地的工具类
* @param args
*/
public static void main(String[] args) {
String txUrl = "网络URl路径";
// 生成视频名称
String spName = System.currentTimeMillis() + ".mp4";
// 保存到本地的地址 /Users/tp/shipi/ 因为我是mac本所以和win系统不一样
// 所以使用win系统的自行更换
// String bdPath = "/Users/tp/shipi/"+spName;
String bdPath = "/var/data/shipi/"+spName; // 保存到服务器的地址
boolean downVideo = downVideo(txUrl, bdPath);
}
/**
* 下载视频
* @param videoUrl 视频网络地址
* @param downloadPath 视频保存地址
*/
public static boolean downVideo(String videoUrl, String downloadPath) {
HttpURLConnection connection = null;
InputStream inputStream = null;
RandomAccessFile randomAccessFile = null;
boolean re;
try {
URL url = new URL(videoUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=0-");
connection.connect();
if (connection.getResponseCode() / 100 != 2) {
System.out.println("连接失败...");
return false;
}
inputStream = connection.getInputStream();
int downloaded = 0;
int fileSize = connection.getContentLength();
randomAccessFile = new RandomAccessFile(downloadPath, "rw");
while (downloaded < fileSize) {
byte[] buffer = null;
if (fileSize - downloaded >= 1000000) {
buffer = new byte[1000000];
} else {
buffer = new byte[fileSize - downloaded];
}
int read = -1;
int currentDownload = 0;
long startTime = System.currentTimeMillis();
while (currentDownload < buffer.length) {
read = inputStream.read();
buffer[currentDownload++] = (byte) read;
}
long endTime = System.currentTimeMillis();
double speed = 0.0;
if (endTime - startTime > 0) {
speed = currentDownload / 1024.0 / ((double) (endTime - startTime) / 1000);
}
randomAccessFile.write(buffer);
downloaded += currentDownload;
randomAccessFile.seek(downloaded);
System.out.printf(downloadPath+"下载了进度:%.2f%%,下载速度:%.1fkb/s(%.1fM/s)%n", downloaded * 1.0 / fileSize * 10000 / 100,
speed, speed / 1000);
}
re = true;
return re;
} catch (MalformedURLException e) {
e.printStackTrace();
re = false;
return re;
} catch (IOException e) {
e.printStackTrace();
re = false;
return re;
} finally {
try {
connection.disconnect();
inputStream.close();
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ps
:一个开发界的小学生,一直在学习从未敢停止
版权声明:本文为m0_45245077原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。