首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在java中拆分和合并回二进制文件。

在java中拆分和合并回二进制文件。
EN

Stack Overflow用户
提问于 2010-12-14 02:04:20
回答 6查看 20.6K关注 0票数 17

我正在尝试将一个二进制文件(如视频/音频/图像)分成每个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;
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4431945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档