我正在尝试将一个二进制文件(如视频/音频/图像)分成每个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;
https://stackoverflow.com/questions/4431945
复制相似问题