2009-09-24 70 views
2

我試圖從文件中創建字節數組塊,該進程仍在使用該文件進行寫入。其實我正在將視頻存儲到文件中,並且我想在錄製時從同一個文件創建塊。如何在寫入文件時將文件拆分爲數據塊?

下面的方法是應該從文件讀取的字節的塊:

private byte[] getBytesFromFile(File file) throws IOException{ 
    InputStream is = new FileInputStream(file); 
    long length = file.length(); 

    int numRead = 0; 

    byte[] bytes = new byte[(int)length - mReadOffset]; 
    numRead = is.read(bytes, mReadOffset, bytes.length - mReadOffset); 
    if(numRead != (bytes.length - mReadOffset)){ 
     throw new IOException("Could not completely read file " + file.getName()); 
    } 

    mReadOffset += numRead; 
    is.close(); 
    return bytes; 
} 

但問題是,所有的數組元素被設置爲0和I估計是因爲寫入過程鎖定該文件。

如果你們中的任何一個人在寫入文件時可以顯示任何其他方式來創建文件塊,我將非常感激。

+0

重複的http://stackoverflow.com/questions/1470600/android-reading-bytes-from-file-with-one-process-while-another-process- is-writin – 2009-09-24 12:25:56

+2

@stephen:找不到頁面。 – Chii 2009-09-24 14:27:49

+0

你自己的應用程序是否編寫了視頻文件(你已經寫過了)?或者您是否嘗試將外部應用程序的輸出分塊? – 2009-10-06 16:04:13

回答

5

問題解決了:

private void getBytesFromFile(File file) throws IOException { 
    FileInputStream is = new FileInputStream(file); //videorecorder stores video to file 

    java.nio.channels.FileChannel fc = is.getChannel(); 
    java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10000); 

    int chunkCount = 0; 

    byte[] bytes; 

    while(fc.read(bb) >= 0){ 
     bb.flip(); 
     //save the part of the file into a chunk 
     bytes = bb.array(); 
     storeByteArrayToFile(bytes, mRecordingFile + "." + chunkCount);//mRecordingFile is the (String)path to file 
     chunkCount++; 
     bb.clear(); 
    } 
} 

private void storeByteArrayToFile(byte[] bytesToSave, String path) throws IOException { 
    FileOutputStream fOut = new FileOutputStream(path); 
    try { 
     fOut.write(bytesToSave); 
    } 
    catch (Exception ex) { 
     Log.e("ERROR", ex.getMessage()); 
    } 
    finally { 
     fOut.close(); 
    } 
} 
0

如果是我,我會通過進程/線程寫入文件來分塊。無論如何,Log4j似乎是這樣做的。應該可以製作一個OutputStream,它會自動開始每N個字節寫入一個新文件。