package com.hh.M3u8;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author
* @create 2020-07-03
*/
public class M3u8Demo {
private static String rootPath = "G:\\m3u8dir";
public static void main(String[] args) {
String indexPath = "http://202.100.35.195:6666/openUrl/JqpcPNC/live.m3u8";
String prePath = indexPath.substring(0,indexPath.lastIndexOf("/")+1);
System.out.println(prePath);
//下载索引文件
String indexStr = getIndexFile(indexPath);
//解析索引文件
List videoUrlList = analysisIndex(indexStr);
//下载视频片段
List<String> fileList = downLoadIndexFile(prePath,videoUrlList);
}
//下载索引文件
public static String getIndexFile(String urlpath){
try{
URL url = new URL(urlpath);
//下在资源
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
String content = "" ;
String line;
while ((line = in.readLine()) != null) {
content += line + "\n";
}
in.close();
System.out.println("下载索引文件 "+content);
return content;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
//解析索引文件
public static List analysisIndex(String content){
Pattern pattern = Pattern.compile(".*ts");
Matcher ma = pattern.matcher(content);
List<String> list = new ArrayList<String>();
while(ma.find()){
String s = ma.group();
list.add(s);
System.out.println("解析文件 "+s);
}
return list;
}
//根据解析结果下载视频片段
public static List<String> downLoadIndexFile(String preUrlPath,List<String> urlList){
try{
List<String> filePathList = new ArrayList<String>();
String uuid = UUID.randomUUID().toString().replaceAll("-","");
for(String urlpath:urlList){
URL url = new URL(preUrlPath+urlpath);
//下在资源
DataInputStream dataInputStream = new DataInputStream(url.openStream());
String fileOutPath = rootPath+ File.separator+uuid+File.separator+urlpath;
File file = new File(rootPath+File.separator+uuid);
if(!file.exists()){
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(new File(fileOutPath));
byte[] bytes = new byte[1024];
int length = 0;
while ((length = dataInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, length);
}
System.out.println("下载完成..."+fileOutPath);
dataInputStream.close();
filePathList.add(fileOutPath);
}
return filePathList;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
原文:https://www.cnblogs.com/Lk-skyhorse/p/13231400.html