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 的做法。应该可以使OutputStream每 N 个字节自动开始写入一个新文件。

于 2009-10-03T10:28:55.640 回答