在Java中拆分并重新加入二进制文件


问题内容

我正在尝试将一个二进制文件(如视频/音频/图像)分成每个100kb的块,然后将这些块重新连接回原来的文件。我的代码似乎可以正常工作,从某种意义上说,它可以分割文件并合并块,我返回的文件大小与原始文件相同。但是,问题在于内容会被截断-
也就是说,如果它是视频文件,它将在2秒钟后停止,如果它是图像文件,则只有上部看起来正确。

这是我正在使用的代码(如果您愿意,我可以发布整个代码):

划分:

File ifile = new File(fname); 
FileInputStream fis;
String newName;
FileOutputStream chunk;
int fileSize = (int) ifile.length();
int nChunks = 0, read = 0, readLength = Chunk_Size;
byte[] byteChunk;
try {
    fis = new FileInputStream(ifile);
    StupidTest.size = (int)ifile.length();
    while (fileSize > 0) {
        if (fileSize <= Chunk_Size) {
            readLength = fileSize;
        }
        byteChunk = new byte[readLength];
        read = fis.read(byteChunk, 0, readLength);
        fileSize -= read;
        assert(read==byteChunk.length);
        nChunks++;
        newName = fname + ".part" + Integer.toString(nChunks - 1);
        chunk = new FileOutputStream(new File(newName));
        chunk.write(byteChunk);
        chunk.flush();
        chunk.close();
        byteChunk = null;
        chunk = null;
    }
    fis.close();
    fis = null;

对于连接文件,我将所有块的名称放入列表中,然后按名称对其进行排序,然后运行以下代码:

File ofile = new File(fname);
FileOutputStream fos;
FileInputStream fis;
byte[] fileBytes;
int bytesRead = 0;
try {
    fos = new FileOutputStream(ofile,true);             
    for (File file : files) {
        fis = new FileInputStream(file);
        fileBytes = new byte[(int) file.length()];
        bytesRead = fis.read(fileBytes, 0,(int)  file.length());
        assert(bytesRead == fileBytes.length);
        assert(bytesRead == (int) file.length());
        fos.write(fileBytes);
        fos.flush();
        fileBytes = null;
        fis.close();
        fis = null;
    }
    fos.close();
    fos = null;

问题答案:

我只能在代码中发现2个潜在错误:

int fileSize = (int) ifile.length();

当文件超过2GB时,以上操作将失败,因为int不能容纳更多文件。

newName = fname + ".part" + Integer.toString(nChunks - 1);

像这样构造的文件名应该以非常特定的方式进行排序。使用默认字符串排序时,name.part10将位于之前name.part2。您想提供一个习惯Comparator,该习惯将零件号提取并解析为一个int,然后以此进行比较。