Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mp4parser;
- import java.io.*;
- import java.util.Enumeration;
- import java.util.Vector;
- public class RandomAccessSequenceFile implements Closeable{
- Enumeration<RandomAccessFile> e;
- private RandomAccessFile rIn;
- private long startOffset = 0;//偏移位置
- private long endOffset = 0;
- private File file = null;//mdathead文件
- public RandomAccessSequenceFile(RandomAccessFile s1, RandomAccessFile s2, long startOffset, long endOffset) throws IOException {
- //startOffset为原文件的偏移起始位置
- this.startOffset = startOffset;
- this.endOffset = endOffset;
- RandomAccessFile mdatHeadIn = getMdatHead(endOffset-startOffset+8);
- Vector<RandomAccessFile> v = new Vector<RandomAccessFile>(2);
- // s2.setLength(endOffset);
- s2.skipBytes((int) startOffset);//跳到偏移字节位置
- v.addElement(s1);
- v.addElement(mdatHeadIn);
- v.addElement(s2);
- e = v.elements();
- try {
- nextStream();
- } catch (IOException ex) {
- // This should never happen
- throw new Error("panic");
- }
- }
- final void nextStream() throws IOException {
- if (rIn != null) {
- rIn.close();
- }
- if (e.hasMoreElements()) {
- rIn = e.nextElement();
- if (rIn == null)
- throw new NullPointerException();
- }
- else{
- file.delete();//删除创建的临时文件
- rIn = null;
- }
- }
- public int read(byte[] bytes) throws IOException {
- // System.out.println("偏移量"+rIn.getFilePointer());
- if(rIn == null){
- return -1;
- }
- do {
- int n = rIn.read(bytes);
- if (n > 0) {
- return n;
- }
- nextStream();
- } while (rIn != null);
- return -1;
- }
- //实现从任意偏移位置开始
- public void seek(long start) throws IOException {
- if(start>0){
- long n = start;
- while (n-rIn.length()>0){
- n-=rIn.length();
- nextStream();
- }
- rIn.seek(n);
- }
- }
- //mdat头部
- private RandomAccessFile getMdatHead(long size) throws IOException {
- byte[] mdathead = {0x00,0x00,0x00,0x00,0x6d,0x64,0x61,0x74};
- for (int i = 0; i < 4; i++) {
- mdathead[i] = (byte) ((size>>((3-i)*8))&0xff);
- // System.out.println(Long.toBinaryString(mdathead[i]));
- }
- // System.out.println(Long.toBinaryString(mdathead[4]&0xff));
- file = File.createTempFile("mdathead",null);
- FileOutputStream out = new FileOutputStream(file);
- out.write(mdathead);
- out.close();
- return new RandomAccessFile(file,"r");
- }
- @Override
- public void close() throws IOException {
- if(rIn!=null)
- rIn.close();
- while (e.hasMoreElements()) {
- rIn = e.nextElement();
- if (rIn == null)
- rIn.close();
- }
- file.delete();//删除创建的临时文件
- rIn = null;
- }
- }
Add Comment
Please, Sign In to add comment