字幕文件srt格式解析

    技术2022-07-11  84

    解析srt文件,封装为list返回

    首先新建个class,表示单个字幕数据的实体类 public class SrtEntity { /** * 字幕序号 */ public int number; /** * 开始时间 */ public String bg; /** * 结束时间 */ public String ed; /** * 字幕内容 */ public String content; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getBg() { return bg; } public void setBg(String bg) { this.bg = bg; } public String getEd() { return ed; } public void setEd(String ed) { this.ed = ed; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }

    2.编写srt转list的方法

    /** * 解析srt文件,封装为list并返回 * @param srtPath */ public List<SrtEntity> getSrtInfoList(String srtPath){ List<SrtEntity> srtList = new ArrayList<>(); try { InputStreamReader read = new InputStreamReader(new FileInputStream(srtPath), "utf-8"); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt; int index = 0; SrtEntity entity = new SrtEntity(); while ((lineTxt = bufferedReader.readLine()) != null){ index ++; switch (index % 4){ case 1 : entity.setNumber(Integer.parseInt(lineTxt)); break; case 2 : String[] timeArray = lineTxt.split(" --> "); entity.setBg(timeArray[0]); entity.setEd(timeArray[1]); break; case 3 : entity.setContent(lineTxt); break; case 0 : srtList.add(entity); entity = new SrtEntity(); break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return srtList; }

    3.测试方法

    public static void main(String[] args) { long begin = System.currentTimeMillis(); FileOperateServiceImpl impl = new FileOperateServiceImpl(); // 解析srt获取list List<SrtEntity> list = impl.getSrtInfoList("E:\\111.srt"); long end = System.currentTimeMillis(); System.out.println(end - begin); }
    Processed: 0.016, SQL: 9