2013-02-26 67 views
0

我需要一些幫助/提示,​​以將基於內存的循環緩衝區轉換爲基於磁盤的...通過對Java文件進行讀/寫操作來存儲一系列圖像。磁盤上的循環緩衝區實現

研究在線我發現我需要:

* 不需要固定大小的幀,但與包括實際尺寸,以及時間戳和標記的報頭前綴的每個幀。然後你可以簡單地記住第一個有效幀頭部的偏移量和最後一個有效幀尾部的偏移量,你就可以實現一個FIFO循環緩衝區。 * 對標題結構使用8的包裝並將緩衝區填充爲8的倍數,以便您可以讀取/寫入文件而不會出現對齊錯誤。

下面是我現在使用的代碼:

class CircularBuffer { 

private ImageIcon buffer[]; 
private int lastIdx; 
private int firstIdx; 
private int size; 
private boolean empty; 

/** default size */ 
static final int DEFAULT_SIZE = 50; 

public CircularBuffer(int size) { 
    this.size = size; 
    this.clear(); 
} 

public CircularBuffer() { 
    this(CircularBuffer.DEFAULT_SIZE); 
} 

public synchronized void push(ImageIcon data) { 
    buffer[this.lastIdx] = data; 
    if(this.lastIdx == this.firstIdx && !this.empty) { 
     this.firstIdx++; 
     this.firstIdx %= this.size; 
      } 
    if (this.empty){ 
     this.empty = false; 
      } 
    this.lastIdx++; 
    this.lastIdx %= this.size; 
} 

public synchronized int getLength() { 
    if (this.empty) 
     return 0; 
    int len = this.lastIdx - this.firstIdx; 
    if (len < 0) 
     len = this.size + len; 
    return len == 0 ? this.size-1 : len; 
} 

public synchronized ImageIcon pop() { 
    if (isEmpty()) { 
     throw new IndexOutOfBoundsException("Empty buffer"); 
    } 
    ImageIcon res = buffer[this.firstIdx]; 
    buffer[this.firstIdx] = null; 
    this.firstIdx++; 
    this.firstIdx %= this.size; 
    if (this.firstIdx == this.lastIdx) 
     this.empty = true; 
    return res; 
} 

public synchronized boolean isEmpty() { 
    return this.empty; 
} 

public void clear() { 
    this.firstIdx = 0; 
    this.lastIdx = 0; 
    this.empty = true; 
    this.buffer = new ImageIcon[size]; 
} 

public int getSize() { 
    return this.size; 
} 

}

感謝您的幫助!

+0

你的問題是什麼? – Nick 2013-02-26 13:44:36

+0

問題:如何修改上面的代碼在磁盤而不是內存上執行操作... – Tekmanoid 2013-02-26 13:48:35

+0

你試過了什麼? – Nick 2013-02-26 13:50:29

回答

0

使用,讓你的java內存MappedByteBuffer .. - >存儲 - >磁盤和陣列都API

+0

謝謝,看起來很有趣! – Tekmanoid 2013-02-26 13:57:37

1

從您的其他問題,我建議你不需要具有任何打擾像基於磁盤的循環緩衝區一樣先進。那麼下面的僞代碼如何:

Start: 
    lastFrame = 0 
    Loop Until STOP_REQUESTED: 
     get_new_image_frame 
     lastFrame++ 
     if (lastFrame > maxFrames) 
     lastFrame = 1 
     EndIf 
     write_image_to_disk_named("image" + lastFrame + ".jpg") 
    EndLoop 

    initialise_video_ready_to_add_frames() 
    Loop: 
     add_image_to_video("image" + lastFrame + ".jpg") 
     lastFrame++ 
     if (lastFrame > maxFrames) 
     lastFrame = 1 
     EndIf 
    EndLoop 
+0

我可能不得不採取更簡單的方式來解決這個問題。 – Tekmanoid 2013-02-26 15:16:27

相關問題