120 下载m3u8文件

2020-07-12  本文已影响0人  滔滔逐浪

package com.taotao.test;

import com.taotao.entity.M3U8;
import com.taotao.util.MD5Util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;

/**
 * @author aping
 * @time 2020/7/6 18:06
 */
public class Test2 {
    public static String TEMP_DIR = "C:/kaifa/gz/VideoTools/hls/2";
    public static int connTimeout = 30 * 60 * 1000;
    public static int readTimeout = 30 * 60 * 1000;
    public static String s1 = "   https://s.69xx06.top/video/bf580f33008e38f4ce97fd135f12115e.m3u8                                                                                                                        ";


    public static void main(String[] args) throws IOException {
        String wjj = MD5Util.getMD5Str(s1.trim());
        System.out.println(wjj+"**********");
        File tfile = new File(TEMP_DIR + File.separator + wjj + File.separator);
        if (!tfile.exists()) {
            tfile.mkdirs();
        }
        File ctafile = new File(TEMP_DIR + File.separator + "c_"+ wjj + File.separator + wjj + ".m3u8");
        File tafile = new File(TEMP_DIR + File.separator + wjj + File.separator + wjj + ".m3u8");
        File fileParent = ctafile.getParentFile();
        if(!fileParent.exists()){
            fileParent.mkdirs();
        }
        ctafile.createNewFile();
        if (!tafile.exists()) {
            tafile.createNewFile();
        }

        M3U8 m3u8ByURL = getM3U8ByURL(s1.trim(),tafile,ctafile);
        String basePath = m3u8ByURL.getBasepath();
        m3u8ByURL.getTsList().stream().parallel().forEach(m3U8Ts -> {
            File file = new File(TEMP_DIR + File.separator + wjj + File.separator + m3U8Ts.getFile() + File.separator);
            //   System.out.println(file.getName() + "*");
            if (!file.exists()) {// 下载过的就不管了
                FileOutputStream fos = null;
                InputStream inputStream = null;
                try {

                    URL url = new URL(m3U8Ts.getFile());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(connTimeout);
                    conn.setReadTimeout(readTimeout);
                    if (conn.getResponseCode() == 200) {
                        inputStream = conn.getInputStream();
                        fos = new FileOutputStream(TEMP_DIR + File.separator + wjj + File.separator + file.getName());// 会自动创建文件
                        int len = 0;
                        byte[] buf = new byte[1024];
                        while ((len = inputStream.read(buf)) != -1) {
                            fos.write(buf, 0, len);// 写入流中
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {// 关流
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        System.out.println("文件下载完毕!");
        //     mergeFiles(tfile.listFiles(), "test.ts");
    }

    public static M3U8 getM3U8ByURL(String m3u8URL,File tafile,File ctafile) throws IOException {
        FileWriter fw = new FileWriter(tafile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        FileWriter fw1 = new FileWriter(ctafile.getAbsoluteFile());
        BufferedWriter bw1 = new BufferedWriter(fw1);
        try {

            HttpURLConnection conn = (HttpURLConnection) new URL(m3u8URL).openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            if (conn.getResponseCode() == 200) {
                String realUrl = conn.getURL().toString();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String basepath = realUrl.substring(0, realUrl.lastIndexOf("/") + 1);

                M3U8 ret = new M3U8();
                ret.setBasepath(basepath);
                String line;
                float seconds = 0;
                int mIndex;
                while ((line = reader.readLine()) != null) {
                   String sline=line;
                    if (line.endsWith(".ts")) {
                        String[] str=sline.split("/");
                        System.out.println();
                       sline=str[str.length-1];
                      System.out.println(sline);
                    }
                    bw.write(sline);
                    bw.write("\r\n");
                    bw1.write(sline);
                    bw1.write("\r\n");
                    if (line.startsWith("#")) {
                        if (line.startsWith("#EXTINF:")) {
                            line = line.substring(8);
                            if ((mIndex = line.indexOf(",")) != -1) {
                                line = line.substring(0, mIndex + 1);

                            }
                            try {
                                seconds = Float.parseFloat(line);
                            } catch (Exception e) {
                                seconds = 0;
                            }
                        }
                        continue;
                    }
                    if (line.endsWith("m3u8")) {

                        return getM3U8ByURL(basepath + line,tafile,ctafile);
                    }
                    ret.addTs(new M3U8.Ts(line, seconds));
                    seconds = 0;
                }
                reader.close();
                return ret;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            bw.close();
            bw1.close();

        }
        return null;
    }



}






上一篇下一篇

猜你喜欢

热点阅读