How do I split a file into chunks while still writing to it?

I tried to create block byte arrays from a file while the process was still using the file to write. I am actually storing the video to a file and I would like to create chunks from the same file while recording.

The next method was to read blocks of bytes from a file:

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;
}

      

But the problem is that all the elements of the array are set to 0 and I think this is because the writing process is blocking the file.

I would be very grateful if any of you could show some other way to create chunks of files when writing to a file.

+2


source to share


2 answers


Problem solved:



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();
    }
}

      

+5


source


If it was me, I would launch it a process / thread writing to a file. This is what Log4j does, anyway. It should be possible to do OutputStream

that automatically starts writing to a new file every N bytes.



0


source







All Articles