【问题标题】:How to split file into chunks while still writing into it?如何在写入文件的同时将文件拆分成块?
【发布时间】:2009-09-24 11:24:54
【问题描述】:

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

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

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,我猜是因为写入过程锁定了文件。

如果你们中的任何人可以展示任何其他在写入文件时创建文件块的方法,我将不胜感激。

【问题讨论】:

  • 您自己的应用程序是否编写视频文件(您已编写)?还是您尝试分块外部应用程序的输出?

标签: java android file-io filestream


【解决方案1】:

解决了问题:

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

【讨论】:

  • 嗨,你可以更新android 11的代码吗?谢谢
【解决方案2】:

如果是我,我会让它被写入文件的进程/线程分块。无论如何,这就是 Log4j 的做法。应该可以创建一个OutputStream,它会每隔 N 个字节自动开始写入一个新文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2018-03-22
    • 2019-02-15
    • 1970-01-01
    • 2018-09-30
    • 2014-05-21
    • 2021-01-12
    相关资源
    最近更新 更多