拆分并加入java中的二进制文件

Vin*_*dey 16 java file-io

我试图把一个二进制文件(如视频/音频/图片)为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;
Run Code Online (Sandbox Code Playgroud)

为了加入文件,我将所有块的名称放在List中,然后按名称对其进行排序,然后运行以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 10

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

int fileSize = (int) ifile.length();
Run Code Online (Sandbox Code Playgroud)

当文件超过2GB时,上述操作失败,因为int无法容纳更多文件.

newName = fname + ".part" + Integer.toString(nChunks - 1);
Run Code Online (Sandbox Code Playgroud)

像这样构造的文件名应该以非常具体的方式排序.使用默认字符串排序时,name.part10就是之前name.part2.您想提供一个自定义项Comparator,它将部件号提取并解析为int,然后进行比较.