java – 如何在仍然写入文件时将文件拆分成块?

我试图从进程仍然使用该文件进行写入的文件创建字节数组块.实际上我将视频存储到文件中,我想在录制时从同一个文件创建块.

以下方法应该从文件中读取字节块:

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,我想这是因为写入过程会锁定文件.

如果你们中的任何人在写入文件时能够显示任何其他创建文件块的方法,我将非常感激.

解决方法:

解决了这个问题:

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();
    }
}
上一篇:C#中使用FilleStream实现视频文件的复制


下一篇:C# ZIP 压缩解压