3

プロセスがまだファイルを書き込みに使用している間に、ファイルからバイト配列ブロックを作成しようとしました。実際、私はビデオをファイルに保存していますが、記録中に同じファイルからチャンクを作成したいと考えています。

次のメソッドは、ファイルからバイトのブロックを読み取ることになっていました。

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 に設定されていることです。これは、書き込みプロセスがファイルをロックしているためだと思います。

ファイルへの書き込み中にファイルチャンクを作成する他の方法を誰かが示すことができれば、非常に感謝しています。

4

2 に答える 2

8

問題を解決しました:

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();
    }
}
于 2009-10-07T08:52:02.853 に答える
0

私の場合、ファイルへのプロセス/スレッドの書き込みによってチャンク化されます。とにかく、これはLog4jがそれを行うように見える方法です。OutputStreamNバイトごとに自動的に新しいファイルへの書き込みを開始するを作成できるはずです。

于 2009-10-03T10:28:55.640 に答える